MongoDB query to get distinct FirstName values from documents

To get distinct FirstName values from documents in MongoDB, use the distinct() method. This method returns an array of unique values for the specified field across all documents in the collection.

Syntax

db.collection.distinct("fieldName")

Sample Data

db.demo303.insertMany([
    {FirstName:"Chris", LastName:"Brown"},
    {FirstName:"John", LastName:"Doe"},
    {FirstName:"Chris", LastName:"Smith"},
    {FirstName:"John", LastName:"Smith"},
    {FirstName:"David", LastName:"Miller"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e4ea0f6f8647eb59e56202f"),
        ObjectId("5e4ea104f8647eb59e562030"),
        ObjectId("5e4ea10df8647eb59e562031"),
        ObjectId("5e4ea121f8647eb59e562032"),
        ObjectId("5e4ea136f8647eb59e562033")
    ]
}

Display all documents from a collection with the help of find() method ?

db.demo303.find().pretty();
{
    "_id": ObjectId("5e4ea0f6f8647eb59e56202f"),
    "FirstName": "Chris",
    "LastName": "Brown"
}
{
    "_id": ObjectId("5e4ea104f8647eb59e562030"),
    "FirstName": "John",
    "LastName": "Doe"
}
{
    "_id": ObjectId("5e4ea10df8647eb59e562031"),
    "FirstName": "Chris",
    "LastName": "Smith"
}
{
    "_id": ObjectId("5e4ea121f8647eb59e562032"),
    "FirstName": "John",
    "LastName": "Smith"
}
{
    "_id": ObjectId("5e4ea136f8647eb59e562033"),
    "FirstName": "David",
    "LastName": "Miller"
}

Example

Following is the query to get the distinct FirstName values ?

db.demo303.distinct("FirstName");
[ "Chris", "John", "David" ]

Key Points

  • The distinct() method returns only unique values from the specified field.
  • Duplicate values are automatically filtered out from the result array.
  • The result is returned as an array of distinct values.

Conclusion

The distinct() method efficiently retrieves unique field values from a MongoDB collection. It eliminates duplicates and returns a clean array of distinct values for analysis and reporting purposes.

Updated on: 2026-03-15T02:21:16+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements