Sambhav Sharma
Sambhav Sharma

Reputation: 5860

MongoDB query on a subarray

I have the following document

{
   "_id" : "someId",
   "name" : "myTeam",
   "team" : [
                {
                    "entity" : "size",
                    "value" : 14
                },
                {
                    "entity" : "returns",
                    "value" : 45
                }
            ]
}

I need to retrieve all the teams that have a value of size > 10. How could I achieve that in mongoDB?

Upvotes: 1

Views: 1234

Answers (3)

tavsta
tavsta

Reputation: 11

Solution for you:

db.collection.find({ "team.value" : { $gt : 10 }, "team.entity": "size" });

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You can do:

db.collection.find( { team: 
                         { $elemMatch: 
                              { value: 
                                  { $gt: 10 },
                                  entity: 'size'
                              } 
                         }
                      }
                  )

Upvotes: 1

evanchooly
evanchooly

Reputation: 6233

You query the array subdocuments directly:

db.collection.find({ "team.value" : { $gt : 10 } });

Upvotes: 0

Related Questions