0

I have a collection with documents that have several layers of nesting, and the bottom level contains some arrays. For instance, something like

{
    "_id": ObjectId("56cad039213484920df2"),
    "foo": "this",
    "res": {
       "res1": {
           "t1": [1, 1, 1, 1, 1, 1]
               }
           }
    ...
}

Now I want to query for a single array index on the bottom level of nesting. I can manage to access the entire array with something like

db.my_db.find({'foo': 'this'}, {'res.res1.t1': 1})

But then from the documentation, I thought that in order to access a single element of this array, let's say at index 2, I should use $slice.

db.my_db.find({'foo': 'this'}, {'res.res1.t1': {$slice: 2}})

However this doesn't seem to work, instead just giving me full documents back.

My question is then, how do I project a single element of an array in an embedded document?

I'm using Mongo version 3.4.1.

Eric Hansen
  • 1,749
  • 2
  • 19
  • 39

1 Answers1

3

You can use $slice to get first(1), last(-1) and any slice. $slice:2 will give you first two elements [1, 1].

You need to use aggregation for any other indexed value.

Use $arrayElemAt aggregator operator to project the index value from array.

Something like

db.my_db.aggregate({$match:{'foo': 'this'}}, {$project:{'element2': {$arrayElemAt: ['$res.res1.t1', 1]}}})

s7vr
  • 73,656
  • 11
  • 106
  • 127