Accessing a value in an embedded document in an array

Consider a document containing an array of embedded documents:

{'array': [{'key1': 120.0, 'key2': 69.0}, {'key1': 100.0, 'key2': 50.0}]}

I want to project key2for the first element of an array.

I naively tried

'$project':
    {
        'item': '$array.0.key2'
    }

which fails (but explains what I want to do better than many words).

Using $ arrayElemAt and $ let

Since MongoDB 3.2, you can get an item from a list using $ arrayElemAt :

'$project':
    {
        'item1': {'$arrayElemAt': ['$array', 0] }
    }

will return item1how {'key1': 120.0, 'key2': 69.0}.

What do I want key2there.

I managed to get it using $ let :

'$project':
    {
        'item': {
            '$let': {
                'vars': {
                    'tmp': {'$arrayElemAt': ['$array', 0] },
                    },
                'in': '$$tmp.key2'
            }
        },
    }

Is there an easier way?

. , ( , ) .

, , , . - ( ) . , .

, . .

+4
2

, :

'$project': {'item1': {'$arrayElemAt': ['$array', 0] }}

:

{$project: {"item1.key2": 1}}
+1

$let. $arrayElemAt $project $$ROOT, . $sort dot . , $project , "item" "_id" .

db.collection.aggregate([
    { "$project": { 
        "item": { "$arrayElemAt": [ "$array", 0 ] },  
        "doc": "$$ROOT"
    }}, 
    { "$sort": { "item.key2": 1 } }, 
    { "$project": { "doc": 1, "_id": 0 } }
])
+2

All Articles