Return Distinct Elements in a Field of a MongoDB Collection

I’ve been working with MongoDB, and I noticed that querying the unique values in a field of a given collection follows a non-idiomatic pattern. That is to say, it does not look like,

db.collection.find( { "Field": { $unique: 1 } } )

Rather, it looks like this,

db.runCommand( { distinct: <collection>, key: <field> } )

And this returns a document with a "values" and "stats" field, and hopefully an "ok":1 field. This is the documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *