Question

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'?

Was it helpful?

Solution

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})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top