davalo
davalo

Reputation: 158

Query array element and then field, from MongoDB

Suppose I have the following document in a collection:

{  
   "_id":ObjectId("1123562e7c594c12942f"),
   "figures":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"triangle",
         "color":"black"
      }
   ]
}

I would like to make a query which selects the field "shape" from the second element of the array "figures".

Using db.test.find({}, {"figures": {$slice: [2, 1]}}) you can access the second element of "figures", but can you also select only the field "shape" from there?

Upvotes: 0

Views: 38

Answers (1)

msvairam
msvairam

Reputation: 872

Use below query

db.test.find({}, {"figures": {$slice: [2, 1]}, "figures.shape": 1}).pretty();

Upvotes: 1

Related Questions