Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-12068

Document behavior of nested array fields when using $arrayElemAt

    XMLWordPrintable

Details

    • Task
    • Status: Open
    • Major - P3
    • Resolution: Unresolved
    • None
    • None
    • Server
    • None

    Description

      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

          Activity

            People

              Unassigned Unassigned
              nick.brewer Nick Brewer
              David Storch David Storch
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                4 years, 2 weeks, 5 days ago