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
Getting a distinct aggregation of an array field across indexes
To get a distinct aggregation of an array field across indexes in MongoDB, use the distinct() method on the array field. MongoDB will automatically utilize any existing index on that field to optimize the operation.
Syntax
db.collection.distinct("arrayFieldName")
Sample Data
Let's create a collection with documents containing array fields ?
db.distinctAggregation.insertMany([
{
"UserName": "Larry",
"UserPost": ["Hi", "Hello"]
},
{
"UserName": "Chris",
"UserPost": ["Hi", "Good Morning"]
},
{
"UserName": "Robert",
"UserPost": ["Awesome"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Display all documents to verify the data ?
db.distinctAggregation.find().pretty();
{
"_id": ObjectId("5c98aefb330fd0aa0d2fe4c6"),
"UserName": "Larry",
"UserPost": [
"Hi",
"Hello"
]
}
{
"_id": ObjectId("5c98af0a330fd0aa0d2fe4c7"),
"UserName": "Chris",
"UserPost": [
"Hi",
"Good Morning"
]
}
{
"_id": ObjectId("5c98af1e330fd0aa0d2fe4c8"),
"UserName": "Robert",
"UserPost": [
"Awesome"
]
}
Create Index on Array Field
Create an index on the array field to optimize distinct operations ?
db.distinctAggregation.createIndex({"UserPost": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Get Distinct Values from Array Field
Use the distinct() method to get unique values across all array elements ?
db.distinctAggregation.distinct("UserPost");
["Awesome", "Good Morning", "Hello", "Hi"]
Key Points
- The
distinct()method flattens array values and returns unique elements across all documents. - MongoDB automatically uses the index on
UserPostto optimize the distinct operation. - Results are returned in sorted order when an index exists on the field.
Conclusion
The distinct() method efficiently extracts unique values from array fields across all documents. Creating an index on the array field improves performance for large collections.
Advertisements
