Return unique values in MongoDB
In this article, we will address how to use the MongoDB distinct() method to return unique values. In addition, returning unique values in arrays and fields is discussed.
In MongoDB, sometimes you may want to present or return unique values, you can do this using the distinct() method.
distinct()
The method generates an array of distinct values for a given field across all collections or views in a single collection or view and helps you return unique values for a specified field in the mongo shell.
distinct() function in MongoDB
grammar:
db.collection.distinct(field, query, options)
In MongoDB, the function must have two required parameters called field and query operator. The field parameter is the field in which you want the distinct() method to get unique values.
The query parameter specifies the document from which the distinct values should be fetched. You can send collateral options parameters to the function.
请注意
If the value of the specified field is an array, distinctdistinct()
() will treat each array element as a separate value. For example, if the value of the field is [10, [10], 10], distinct() will treat 10, [10], and 10 as separate values.
Use the distinct() function to return unique values
Let's use distinct()
the function to return unique values in MongoDB. The following 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
}
Returns unique or distinct values for a field in MongoDB
The movies collection above returns unique values for the field specified in this example. Suppose you want unique values in the ratings field.
Query:
db.movies.distinct( "rating" )
[ null, "", "NC-17", "PG", "PG-13"]
After using the above query, distinct()
the function has successfully helped you return unique values for a collection in MongoDB.
Return unique values for embedded fields in MongoDB
In this example, returning unique values for an embedded field is shown. However, the collection used in the previous example does not contain an embedded field.
Therefore, 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 returns unique values from all embedded fields in the above database collection.
Query:
db.drones.distinct( "additionalDetails.material" )
[ "aluminum", "carbon fiber", "glass fiber"]
Returns the unique values of 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 will learn in detail about different functions with collections. Returning arrays and unique values in a field or embedded fields are also explained with code snippets.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$unset operator in MongoDB
Publish Date:2025/04/27 Views:77 Category:MongoDB
-
This article will discuss how the $unset operator works in MongoDB. Additionally, we will demonstrate the use of this operator to remove a field from all documents in a MongoDB collection. $unset operator in MongoDB $unset is an operator us
Compass Filters in MongoDB
Publish Date:2025/04/27 Views:132 Category:MongoDB
-
This short article will cover the various ways to use Compass filters in MongoDB . Compass Filters in MongoDB MongoDB has a GUI called Compass . It is also known as MongoDB GUI. Users can use MongoDB to inspect the contents of their stored
Sorting by timestamp in MongoDB
Publish Date:2025/04/27 Views:54 Category:MongoDB
-
This article will introduce various methods of sorting timestamps in MongoDB. Sorting by timestamp in MongoDB sort() The method will sort documents in MongoDB. The method accepts a document containing a list of fields and the order in which
Deleting a user from a database in MongoDB
Publish Date:2025/04/27 Views:50 Category:MongoDB
-
This article will explain how to delete a user from a MongoDB database. In addition, we will see an example to make the topic easier to understand. Deleting a User from a MongoDB Database Sometimes we need to remove a particular user from t
Deleting items by ID in MongoDB
Publish Date:2025/04/27 Views:158 Category:MongoDB
-
Sometimes we need to delete data from a database based on specified criteria. Unlike other SQL databases, MongoDB does not include SQL queries for this purpose. Instead, it uses commands. This article will discuss how to delete documents ba
Using ISODate for date queries in MongoDB
Publish Date:2025/04/27 Views:77 Category:MongoDB
-
This MongoDB tutorial article will explain Date() the methods. This article introduces different ways to query using dates. Date() Method in MongoDB Date() The method returns the date as a string or a Date object. In the MongoDB shell or mo
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato