MongoDB distinct() – Return Only Unique Values in MongoDB

Return Only Unique Values Featured Image

In this guide, I will explain to you how to return only unique values using MongoDB distinct().

There might be times when you want to render or return only unique values in MongoDB. we can achieve this using the distinct() function in MongoDB.

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

This guide aims to explain with examples return only unique values in MongoDB. so, let us get started with the guide!

Also read: Using the getIndexes() Function in MongoDB

The distinct() Function Syntax in MongoDB

Let us take a quick look at the distinct() function syntax in MongoDB:

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

the function must be provided with two mandatory parameters called the field and query operator in MongoDB. The field parameter is a field that we want the unique values to be retrieved from using the distinct() function.

Second is the query parameter which indicates the documents from which the distinct values should be retrieved. Lastly, you can even pass a collateral options parameter to the function.

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

Let us get started with using the distinct() function to be able to return only unique values in MongoDB.

To start off, I will be using the below collection for at least the first example.

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

Returning Unique or Distinct Values for a Field in MongoDB

In this example, I will use the above movies collection to return only unique values for the specified field. Let’s say 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

In this example, I will be returning unique values for an embedded field this time. However, the collection we used in the previous example didn’t contain embedded fields. Hence, I 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 Field

In this example, I will be using the same collection as above to return only unique values from an embedded array field using the distinct() function.

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

Perfect! We have here our array of unique values.

Conclusion

Learn to use the return only unique values in MongoDB using the distinct() function inside the mongo shell for a field.

While this function really only returns the unique field values, there might be times when we want full records, meaning complete documents that matched our distinct query.

In this case, we want to use something called the aggregation distinct.

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/