MongoDB distinct() – Return Only Unique Values in MongoDB

Sometimes you want to return only unique values in MongoDB which can be achieved by using the distinct() function.

The distinct() function returns an array of unique values for a specified field across a single collection. It eventually helps us return only unique values for a field we specify in the mongo shell.

Also Read: Using the getIndexes() Function in MongoDB

MongoDB distinct() Function

Below is the syntax for using the MongoDB distinct() function to perform a distinct operation in MongoDB.

Syntax:

db.collection.distinct(field, query, options)

Parameters:

The function must be provided with two mandatory parameters, field and query.

  • field is a field that we want the unique values to be retrieved from using the distinct() function,
  • query indicates the documents from which the distinct values should be retrieved,
  • options is a collation optional parameter that is not mandatory to pass

Return:

This returns an array that contains individual values for the fields specified according to the query pass.

Note: If the specified field’s value is an array, distinct() treats each element of the array as a separate value. For example, if a field has the value [10, [10], 10], distinct() treats 10, [10], and 10 as separate values.

How to Return Only Unique Values Using the distinct() Function

The distinct() function is able to return only specific values ​​for a field in MongoDB by passing the field name as an argument to this function.

Example:

We will use the below collection as an example to demonstrate this function.

> db.movies.find().pretty()
{
        "_id" : ObjectId("60322d3501cd70079c48cb65"),
        "title" : "Enchanted",
        "year" : 2006,
        "score" : 10,
        "rating" : "PG",
        "__v" : 0
}
{
        "_id" : ObjectId("60322d3501cd70079c48cb67"),
        "title" : "Final Destination II",
        "year" : 2015,
        "score" : 10,
        "rating" : "PG-13",
        "__v" : 0
}
{
        "_id" : ObjectId("6190189ef5c8903629012fe1"),
        "title" : "Fifty Shades of Grey",
        "year" : 2015,
        "score" : 10,
        "rating" : "NC-17",
        "__v" : 0
}
{
        "_id" : ObjectId("6190189ef5c8903629012fe2"),
        "title" : "Cars",
        "year" : 2006,
        "score" : 8,
        "rating" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("6190189ef5c8903629012fe3"),
        "title" : "The Matrix",
        "year" : 1999,
        "score" : null,
        "rating" : "R",
        "__v" : 0
}
{
        "_id" : ObjectId("61901f82f5c8903629012fe4"),
        "title" : "Salt",
        "year" : 2010,
        "score" : 9,
        "rating" : "",
        "__v" : 0
}
{
        "_id" : ObjectId("61901f82f5c8903629012fe5"),
        "title" : "Knowing",
        "year" : 2009,
        "score" : 8,
        "rating" : "",
        "__v" : 0
}
{
        "_id" : ObjectId("61924e7512800ff6d3639076"),
        "title" : "The Revenant",
        "year" : 2015,
        "score" : 6,
        "rating" : "R",
        "__v" : 0
}
{
        "_id" : ObjectId("61924e7512800ff6d3639077"),
        "title" : "Maleficient: The Mistress of Evil",
        "year" : 2019,
        "score" : 10,
        "rating" : "PG",
        "__v" : 0
}

Use the distinct() function to get the rating field:

> db.movies.distinct( "rating" )
[ null, "", "NC-17", "PG", "PG-13", "R" ]

Here we go! The distinct() function has successfully helped us return only unique values in MongoDB for a collection.

Returning Distinct Values for an Embedded Field in MongoDB

We can also get unique values for an embedded field using the distinct() function.

Example:

In this example, we will return unique values for an embedded field. The collection we used in the previous example didn’t contain embedded documents. Hence, we will use a new collection as shown below:

> db.drones.find().pretty()
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0c"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Nimbari Gryphon Medeta 65",
        "price" : 77500,
        "weight" : "77 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Cinematography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0d"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "X-Strimmer Eye",
        "price" : 23500,
        "weight" : "24 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Precision Agriculture",
                        "Cinematography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0e"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Khai Balemosh Shefqa TRX",
        "price" : 120500,
        "weight" : "80 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0f"),
        "utility" : [
                "Natural Resource Exploration",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Sifinist Croma AX",
        "price" : 99500,
        "weight" : "97 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf10"),
        "utility" : [
                "Remote sensing",
                "Real estate and construction",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Drovce Finnifield FR-7",
        "price" : 87600,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "polysterene",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}

Returning unique values for an embedded field from the above collection:

> db.drones.distinct( "additionalDetails.material" )
[ "aluminum", "carbon fiber", "glass fiber", "lithium", "polysterene" ]

Returning Unique Values for an Embedded Array Fields

We can also return unique values for an embedded array field using the distinct() function.

Example:

> db.drones.distinct( "additionalDetails.moreUses" )
[
        "Cinematography",
        "Land Inspection",
        "Precision Agriculture",
        "Videography",
        "Water Inspection"
]

Perfect! The distinct() method returns the array of unique values.

The distinct() function only returns the unique field values, sometimes you may want to get a full record, i.e., the entire document that matched the distinct query. For this, you can use aggregation distinct.

Conclusion

In this tutorial, we learned about MongoDB’s distinct() function. The distinct() function can be used to return the unique value based on the field and query passed as an argument to this method.

References

https://stackoverflow.com/questions/28155857/mongodb-find-query-return-only-unique-values-no-duplicates

https://docs.mongodb.com/manual/reference/method/db.collection.distinct/

Aneesha S
Aneesha S
Articles: 172