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
List all values of a certain field in MongoDB?
To get the list of all values of certain fields in MongoDB, you can use the distinct() method. This method returns an array of unique values for a specified field across all documents in a collection.
Syntax
db.collectionName.distinct("fieldName");
Create Sample Data
Let us create a collection with sample documents to demonstrate the distinct() method ?
db.listAllValuesDemo.insertMany([
{"ListOfValues": [10, 20, 30]},
{"ListOfValues": [40, 50, 60]},
{"ListOfValues": [10, 20, 30]},
{"ListOfValues": [40, 50, 70]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8fc89ed3c9d04998abf011"),
ObjectId("5c8fc8abd3c9d04998abf012"),
ObjectId("5c8fc8d7d3c9d04998abf013"),
ObjectId("5c8fc8e2d3c9d04998abf014")
]
}
View Sample Data
Display all documents from the collection using find() method ?
db.listAllValuesDemo.find().pretty();
{
"_id": ObjectId("5c8fc89ed3c9d04998abf011"),
"ListOfValues": [10, 20, 30]
}
{
"_id": ObjectId("5c8fc8abd3c9d04998abf012"),
"ListOfValues": [40, 50, 60]
}
{
"_id": ObjectId("5c8fc8d7d3c9d04998abf013"),
"ListOfValues": [10, 20, 30]
}
{
"_id": ObjectId("5c8fc8e2d3c9d04998abf014"),
"ListOfValues": [40, 50, 70]
}
Get Distinct Values
Here is the query to get all distinct values of the 'ListOfValues' field ?
db.listAllValuesDemo.distinct("ListOfValues");
[10, 20, 30, 40, 50, 60, 70]
Key Points
- The
distinct()method returns unique values only, eliminating duplicates. - For array fields, it flattens the arrays and returns all unique elements.
- Results are returned as an array of values.
Conclusion
The distinct() method is an efficient way to retrieve all unique values from a specific field across documents in a MongoDB collection. It automatically handles duplicates and returns a clean array of distinct values.
Advertisements
