MongoDB: Finding distinct items in a collection

The distinct command in MongoDB, find the distinct values for a specified field across a single collection.

The command takes the following form:

{ distinct: "<collection>", key: "<field>", query: <query> }

Examples: Return an array of the distinct values of the field name from all documents in the profile collection:

db.runCommand ( { distinct: "profile", key: "name" } )

or

db.profile.distinct('name')

to get the number of unique names

db.profile.distinct('name').length

Return an array of the distinct values of the field name from the documents in the profile collection where the age is greater than 25:

db.runCommand ( { distinct: "profile", key: "name", query: { age: { $gt: 25 } } } )

2 thoughts on “MongoDB: Finding distinct items in a collection

  1. thanks! really helped.
    The only thing that I need to find now is how to do length on this syntax:

    db.runCommand ( { distinct: “profile”, key: “name”, query: { age: { $gt: 25 } } } )

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s