
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] }
Advertisements