1

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}}})

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It checks for a value as well. Mongodb is truely awesome :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.