-
Type: Task
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Server
-
Labels:
-
2
Notes 2.0
Repurposing this ticket to add more information on field paths and array behavior. Suggestion is to link the field path section in the aggregation quick reference page to a larger section on field paths (potentially a new page). Then, link the new field paths section/page to operator pages that might have use cases for field paths .
Notes 1.0
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.)
- related to
-
SERVER-37246 $arrayElemAt aggregation, referencing property within an array element object, indexes don't include elements without that property.
- Closed