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?
. , ( , ) .
, , , . - ( ) . , .
, . .