

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ] }
- Related Questions & Answers
- Return a list from different rows into a single field with MySQL
- MongoDB aggregation with equality inside array?
- MongoDB aggregation group and remove duplicate array values?
- Specify all the list properties into a single expression with CSS
- MongoDB aggregation of elements with similar ids in different documents?
- Join Map values into a single string with JavaScript?
- MongoDB aggregate to convert multiple documents into single document with an array?
- MongoDB Aggregation to slice array inside array
- Working with Aggregation to match all the values in MongoDB
- MongoDB aggregation with multiple keys
- MongoDB aggregation to sum individual properties on an object in an array across documents
- Inserting multiple parameter values into a single column with MySQL?
- Cannot push into an array from MongoDB?
- A single MySQL query to search multiple words from different column values
- Unset an attribute from a single array element in MongoDB?
Advertisements