Mongo shell, how to find/aggregate embedded documents with lists

96 views Asked by At

I'm trying to aggregate/find data on subdocument that have lists of documents....

I have a mongo document that looks similar to this,

{'town-name': 'anyplace ville',
 'locations': {
     'sports': [ 
          {'name': 'football world', 'audience': 10}, 
          {'name': 'abc', 'audience': 8},..
          ],

     'food': [ 
          {'name': 'pizza world', 'audience': 25}, 
          {'name': 'm&ms', 'audience': 63},..
          ],
  }
}

How can I find/aggregate the sub document of 'sports' or 'food' whose items are lists of documents?

For example I'm trying to find the town-name's of places where 'sports' audiences are greater than 10 or 'food' names are equal to 'm&ms'?

1

There are 1 answers

0
Parvin Gasimzade On BEST ANSWER

The following query lists the town-name's where sports audiences are greater than 10.

db.test.find({"locations.sports.audience" : {$gt:10}},{"town-name":1})

This one will list the town-name's where food names are equal to m&ms

db.test.find({"locations.food.name" : "m&ms"},{"town-name":1})