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
Merge two array fields in MongoDB?
To merge two array fields in MongoDB, use the $setUnion operator in an aggregation pipeline. This operator combines arrays and automatically removes duplicates while preserving unique values from both arrays.
Syntax
db.collection.aggregate([
{
$project: {
"MergedFieldName": {
$setUnion: ["$arrayField1", "$arrayField2"]
}
}
}
]);
Sample Data
db.mergeTwoArrayFieldDemo.insertOne({
"NaturalNumbers": [1, 2, 3, 8, 10, 20, 30],
"WholeNumbers": [0, 1, 2, 63, 78, 20, 45]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd68e4057806ebf1256f11d")
}
Display the inserted document ?
db.mergeTwoArrayFieldDemo.find().pretty();
{
"_id": ObjectId("5cd68e4057806ebf1256f11d"),
"NaturalNumbers": [1, 2, 3, 8, 10, 20, 30],
"WholeNumbers": [0, 1, 2, 63, 78, 20, 45]
}
Example: Merge Two Arrays
Merge the NaturalNumbers and WholeNumbers arrays into a single array ?
db.mergeTwoArrayFieldDemo.aggregate([
{
$project: {
"MergedArray": {
$setUnion: ["$NaturalNumbers", "$WholeNumbers"]
}
}
}
]);
{
"_id": ObjectId("5cd68e4057806ebf1256f11d"),
"MergedArray": [0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78]
}
Key Points
-
$setUnionautomatically removes duplicates (notice 1, 2, and 20 appear only once in the result). - The resulting array is sorted in ascending order.
- Both original fields are preserved unless you specify otherwise in the projection.
Conclusion
Use $setUnion in an aggregation pipeline to merge array fields while eliminating duplicates. This operator is ideal when you need a clean, unified array from multiple sources.
Advertisements
