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
Select two fields and return a sorted array with their distinct values in MongoDB?
To select two fields and return a sorted array with their distinct values in MongoDB, use the aggregation framework with the $setUnion operator. This operator combines arrays and automatically removes duplicates while maintaining sorted order.
Syntax
db.collection.aggregate([
{ $group: {
"_id": null,
"field1Array": { $push: "$field1" },
"field2Array": { $push: "$field2" }
}},
{ $project: {
"_id": 0,
"distinctValues": { $setUnion: ["$field1Array", "$field2Array"] }
}}
]);
Sample Data
db.sortedArrayWithDistinctDemo.insertMany([
{ value1: 4, value2: 5 },
{ value1: 5, value2: 6 },
{ value1: 7, value2: 4 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc690b99cb58ca2b005e666"),
ObjectId("5cc690b99cb58ca2b005e667"),
ObjectId("5cc690b99cb58ca2b005e668")
]
}
Display all documents to verify the data ?
db.sortedArrayWithDistinctDemo.find();
{ "_id": ObjectId("5cc690b99cb58ca2b005e666"), "value1": 4, "value2": 5 }
{ "_id": ObjectId("5cc690b99cb58ca2b005e667"), "value1": 5, "value2": 6 }
{ "_id": ObjectId("5cc690b99cb58ca2b005e668"), "value1": 7, "value2": 4 }
Example
Select the "value1" and "value2" fields and return a sorted array with their distinct values ?
db.sortedArrayWithDistinctDemo.aggregate([
{ $group: {
"_id": null,
"value1": { $push: "$value1" },
"value2": { $push: "$value2" }
}},
{ $project: {
"_id": 0,
"bothValues": { $setUnion: ["$value1", "$value2"] }
}}
]);
{ "bothValues": [4, 5, 6, 7] }
How It Works
-
$groupwith$pushcollects all values from both fields into separate arrays -
$setUnioncombines the arrays, removes duplicates, and sorts the result automatically - The duplicate value 4 and 5 appear only once in the final output
Conclusion
The $setUnion operator efficiently combines multiple field values into a single sorted array with distinct values. This approach is ideal for creating unified value sets from different document fields.
Advertisements
