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
Combining unique items from arrays in MongoDB?
To combine unique items from arrays in MongoDB, use the aggregation pipeline with $concatArrays, $setDifference, and $addToSet operators to merge array values and remove duplicates.
Syntax
db.collection.aggregate([
{
$project: {
combinedArray: {
$setDifference: [
{ $concatArrays: ["$array1", "$array2", "$array3"] },
[]
]
}
}
},
{ $unwind: "$combinedArray" },
{ $group: { _id: null, uniqueItems: { $addToSet: "$combinedArray" } } }
]);
Sample Data
db.demo420.insertMany([
{
"details": [
{
"Value1": 10,
"Value2": 20,
"Value3": 30
}
]
},
{
"Info": [
{
"Value1": 10,
"Value2": 20,
"Value3": 300
}
]
}
]);
WriteResult({ "nInserted": 2 })
Example: Combining Unique Values from Object Fields
Extract and combine unique values from nested object fields ?
db.demo420.aggregate([
{
"$project": {
"_id": 0,
"unique": {
"$filter": {
"input": {
"$setDifference": [
{
"$concatArrays": [
"$Info.Value1",
"$Info.Value2",
"$Info.Value3"
]
},
[]
]
},
"cond": { "$ne": [ "$$this", "" ] }
}
}
}
},
{ "$unwind": "$unique" },
{
"$group": {
"_id": null,
"uniqueArray": { "$addToSet": "$unique" }
}
}
]);
{ "_id": null, "uniqueArray": [ 300, 20, 10 ] }
How It Works
-
$concatArraysmerges multiple arrays into a single array -
$setDifferenceremoves null/empty values by comparing with an empty array -
$filterexcludes empty strings and unwanted values -
$unwinddeconstructs the array into individual documents -
$addToSetcollects unique values, automatically removing duplicates
Conclusion
Use MongoDB's aggregation pipeline with $concatArrays and $addToSet to combine arrays and automatically extract unique values. The $setDifference and $filter operators help clean unwanted elements from the result.
Advertisements
