Darshan Pandit
Darshan Pandit

Reputation: 178

Mongodb Complex Object Query

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

Answers (2)

Rohit Jain
Rohit Jain

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

Eric
Eric

Reputation: 2884

db.collectionName.distinct('location.city') should do the trick.

Upvotes: 1

Related Questions