Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to gather unique array item?
To gather unique array items from a MongoDB collection, use the distinct() method. This method returns an array of unique values for a specified field, automatically removing duplicates.
Syntax
db.collection.distinct("fieldName")
Sample Data
Let us create a collection with documents ?
db.demo588.insertOne({
"CountryName": ["US", "AUS", "UK", "US", "UK", "AUS"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e92bbd2fd2d90c177b5bccb")
}
Display all documents from the collection ?
db.demo588.find().pretty();
{
"_id": ObjectId("5e92bbd2fd2d90c177b5bccb"),
"CountryName": [
"US",
"AUS",
"UK",
"US",
"UK",
"AUS"
]
}
Example: Get Unique Array Values
Following is the query to gather unique array items ?
db.demo588.distinct("CountryName");
["AUS", "UK", "US"]
Key Points
- The
distinct()method automatically removes duplicate values from arrays. - Results are returned as a sorted array of unique values.
- Works on both array fields and regular fields across multiple documents.
Conclusion
Use MongoDB's distinct() method to extract unique values from array fields. It efficiently handles duplicate removal and returns a clean array of distinct values.
Advertisements
