How to Return Unique Values in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. the distinct() Function in MongoDB
  2. Use the distinct() Function to Return Unique Values
  3. Return Unique or Distinct Values for a Field in MongoDB
  4. Return Unique Values for an Embedded Field in MongoDB
  5. Returning Unique Values for an Embedded Array Field
How to Return Unique Values in MongoDB

In this article, we’ll tackle how to return unique values using MongoDB distinct() method. Additionally, returning unique values in arrays and fields is also discussed.

In MongoDB, you may want to render or return unique values at times, and you can accomplish this by utilizing the distinct() method.

The distinct() method produces an array of distinct values for a given field across all collections or views in a single collection or view and assists you in returning unique values for a field specified in the mongo shell.

the distinct() Function in MongoDB

Syntax:

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

In MongoDB, the function must have two necessary parameters called the field and query operator. The field parameter is a field where you want the distinct() method to obtain the unique values.

The query parameter specifies the documents from which the distinct values should be fetched. You may send the function a collateral options parameter.

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

Use the distinct() Function to Return Unique Values

Let’s use the distinct() function to return unique values in MongoDB. The below collection will be used for 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
}

Return Unique or Distinct Values for a Field in MongoDB

The above movie collection returns unique values for the specified field in this example. Let’s say you want unique values from the rating field.

Query:

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

After using the above query, the distinct() function has successfully helped you return unique values in MongoDB for a collection.

Return Unique Values for an Embedded Field in MongoDB

In this example, returning unique values for an embedded field is shown. However, the collection used in the previous example didn’t contain embedded fields.

Hence, a new collection will be used, 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"
                ]
        }
}

The following query can return unique values from all embedded fields from the database collection above.

Query:

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

Returning Unique Values for an Embedded Array Field

Using the distinct() function, you can use the same collection above to return unique values from an embedded array field using the distinct() function.

Query:

db.drones.distinct( "additionalDetails.moreUses" )
["Cinematography","Land Inspection"]

In this MongoDB tutorial article, you are given a detailed view of distinct functions with collections. Returning unique values in arrays and fields or embedded fields is also explained with code segments.

Related Article - MongoDB Query