Coalesce values from different properties into a single array with MongoDB aggregation


To coalesce values means to merge them. To merge them into a single array, use $project in MongoDB.

Let us create a collection with documents −

> db.demo244.insertOne({"Value1":10,"Value2":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4582e31627c0c63e7dba63")
}
> db.demo244.insertOne({"Value1":20,"Value2":30});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4582f11627c0c63e7dba64")
}

Display all documents from a collection with the help of find() method −

> db.demo244.find();

This will produce the following output −

{ "_id" : ObjectId("5e4582e31627c0c63e7dba63"), "Value1" : 10, "Value2" : 20 }
{ "_id" : ObjectId("5e4582f11627c0c63e7dba64"), "Value1" : 20, "Value2" : 30 }

Following is the query to coalesce values from different properties into a single array with MongoDB aggregation −

> db.demo244.aggregate([
...
...   { "$group": {
...      "_id": null,
...      "v1": { "$addToSet": "$Value1" },
...      "v2": { "$addToSet": "$Value2" }
...   }},
...
...   { "$project": {
...      "AllValues": { "$setUnion": [ "$v1", "$v2" ] }
...   }}
...]);

This will produce the following output −

{ "_id" : null, "AllValues" : [ 10, 20, 30 ] }

Updated on: 30-Mar-2020

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements