Austin
Austin

Reputation: 43

How to access the last position in a nested array

I have the following json and want to access the last value in the list contained within 'index_2'. What do I need to add to find({}, {"attributes.index_2":1}) to return only the last position value within the index_2 list.

'name': 'fred',
'attributes': [   {   
      'index_1': [   [   1, 2, 3, 4, 5 ]  ],
      'index_2': [   [   6, 7, 8, 9, 10] ],
      'line_number': 999
    }  ]

Upvotes: 2

Views: 434

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You actually need .aggregate() and the $arrayElemAt aggregation operator here.

Also note that "attributes" is itself an "array", so it depends if you only want it's first element or "all" of it's own entries.

For all use $map:

db.collection.aggregate([
  { "$project": {
    "index_2": {
      "$map": {
        "input": "$attributes",
        "as": "attr",
        "in": {
          "$arrayElemAt": [ "$$attr.index_2", -1 ]
        }
      }
    }
  }}
])

Would produce on your sample:

{ "index_2s": [ 10 ] }

But do note that since "attributes" is an array, then any other array items would also be similarly extracted in the list, or return null if the field did not exist.

The alternate is to combine with $arrayElemAt again to extract the index from the "attributes" input itself:

db.collection.aggregate([
  { "$project": {
    "index_2": {
      "$arrayElemAt": [
        { "$map": {
          "input": "$attributes",
          "as": "attr",
          "in": {
            "$arrayElemAt": [ "$$attr.index_2", -1 ]
          }
        }},
        0
      ]
    }
  }}
])

Which returns just the "first" or 0 index element as a value:

{ "index_2": 10  },

So it's really not clear in the question why "attributes" is an array itself, being whether there are possibly more entries or if for some reason you are only storing one index within it. But those are your options to at least access the "inner" element at the last position.

Upvotes: 1

Related Questions