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