Description
Notes
See below. It seems like we could highlight this behavior by linking to https://www.mongodb.com/docs/manual/tutorial/query-array-of-documents/, perhaps in an admonition.
Description
Currently the $arrayElemAt documentation does not include an example of how it behaves when dot notation is used to reference a nested field name within an array.
A simplified example:
With the following data:
{
|
"_id" : ObjectId("5ba53172ce6fa2fcfc58e0ac"),
|
"example" : [
|
{
|
"apples" : [
|
"macintosh",
|
"golden delicious",
|
"fuji",
|
"gala"
|
]
|
},
|
{
|
"oranges" : [
|
"mandarin",
|
"navel",
|
"clementine"
|
]
|
},
|
{
|
"apples" : [
|
"braeburn",
|
"honeycrisp",
|
"red"
|
]
|
}
|
]
|
}
|
You can include the nested field "apples", and the index value will determine whether you get the first entry in the "example" array, or the third:
db.fruits.aggregate([
|
{
|
"$project": {
|
"apples2": {
|
"$arrayElemAt": ["$example.apples", 1]
|
}
|
}
|
}
|
])
|
This returns the second array that matches the "apples" field name:
{
|
"_id" : ObjectId("5ba53172ce6fa2fcfc58e0ac"),
|
"apples2" : [
|
"braeburn",
|
"honeycrisp",
|
"red"
|
]
|
}
|
Instead of simply returning the second nested field in the "example" array ("oranges"), which would be returned if the 1 index was used without specifying a nested field:
db.fruits.aggregate([
|
{
|
"$project": {
|
"apples2": {
|
"$arrayElemAt": ["$example", 1]
|
}
|
}
|
}
|
])
|
returns:
{
|
"_id" : ObjectId("5ba53172ce6fa2fcfc58e0ac"),
|
"apples2" : {
|
"oranges" : [
|
"mandarin",
|
"navel",
|
"clementine"
|
]
|
}
|
}
|
Scope of changes
Impact to Other Docs
MVP (Work and Date)
Resources (Scope or Design Docs, Invision, etc.)
Attachments
Issue Links
- related to
-
SERVER-37246 $arrayElemAt aggregation, referencing property within an array element object, indexes don't include elements without that property.
-
- Closed
-