
- 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
Merge two array fields in MongoDB?
To merge, use $setUnion operator. Let us first create a collection with documents −
> db.mergeTwoArrayFieldDemo.insertOne({"NaturalNumbers":[1,2,3,8,10,20,30],"WholeNumbers":[0,1,2,63,78,20,45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68e4057806ebf1256f11d") }
Following is the query to display all documents from a collection with the help of find() method −
> db.mergeTwoArrayFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "NaturalNumbers" : [ 1, 2, 3, 8, 10, 20, 30 ], "WholeNumbers" : [ 0, 1, 2, 63, 78, 20, 45 ] }
Following is the query to merge two array field in MongoDB.
> db.mergeTwoArrayFieldDemo.aggregate([ { "$project": { "MergedArray": { "$setUnion": [ "$NaturalNumbers", "$WholeNumbers" ] } }} ]);
This will produce the following output −
{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "MergedArray" : [ 0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78 ] }
- Related Questions & Answers
- MongoDB order by two fields sum?
- MongoDB aggregation to combine or merge fields and then count?
- MongoDB query condition to compare two fields?
- Find sum of fields inside array in MongoDB?
- Select two fields and return a sorted array with their distinct values in MongoDB?
- How to compare two fields in aggregation filter with MongoDB?
- Concatenate fields in MongoDB?
- Best way to sum array size fields in MongoDB?
- Sort array in MongoDB query and project all fields?
- Concatenate strings from two fields into a third field in MongoDB?
- MongoDB query to return specific fields from an array?
- Match MongoDB documents with fields not containing values in array?
- Merge two sets in Java
- MongoDB query to concatenate values of array with other fields
- MongoDB query to get only specific fields in nested array documents?
Advertisements