Reputation: 178
I want to find distinct values of the cities from a collection containing objects as mentioned below:
{
location:{
address:'XYZ',
city:'New York'
}
}
Can you help me with the query I need to fire? I know I have to use elemMatch
and $exists
. But my following query seem to work and returns an empty set:
db.collectionName.distinct({'location':{'city':{$exists: true}}})
Upvotes: 1
Views: 911
Reputation: 213263
db.collection.distinct
takes the query as a 2nd parameter.
Here's how you should do it: -
db.collectionName.distinct('location.city', {'location.city': {$exists: true}})
Additionally, you can also use this distinct
database command: -
db.runCommand({ "distinct": "collectionName",
"key": "location.city",
"query": {'location.city' : {$exists: true}}
}).values
Upvotes: 3