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

5 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 comment