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
How to merge multiple documents in MongoDB?
To merge multiple documents in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo436.insertOne(
... {
... "_id" : "101",
... "Name": "Chris",
... "details" : [
... {
... "CountryName" : "US",
... "Age" : 21
... }
... ],
... "Price" : 50
... }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo436.insertOne(
... {
... "_id" : "102",
... "Name": "Chris",
... "details" : [
... {
... "CountryName" : "UK",
... "Age" : 22
... }
... ],
... "Price" : 78
... }
... );
{ "acknowledged" : true, "insertedId" : "102" }
> db.demo436.insertOne(
... {
... "_id" : "103",
... "Name": "Chris",
... "details" : [
... {
... "CountryName" : "US",
... "Age" : 21
... }
... ],
.. . "Price" : 50
... }
... );
{ "acknowledged" : true, "insertedId" : "103" }
Display all documents from a collection with the help of find() method −
> db.demo436.find();
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }
{ "_id" : "102", "Name" : "Chris", "details" : [ { "CountryName" : "UK", "Age" : 22 } ], "Price" : 78 }
{ "_id" : "103", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }
Following is the query to merge multiple documents in MongoDB −
> db.demo436.aggregate([
... {$sort: {_id: 1, Name: 1}},
... {$unwind: '$details'},
... {$group: {_id: '$Name', details: {$push: '$details'},
... Price: {$sum: '$Price'},
... id: {$last: {$concat: ["$_id", "_", "AppendedValue" ]}},
... Name: {$last: '$Name'}}},
... {$addFields: {Id: 'NewIdAppped', _id: '$id'}},
... {$project: {"id": 0 }}])
This will produce the following output −
{ "_id" : "103_AppendedValue", "details" : [ { "CountryName" : "US", "Age" : 21 }, { "CountryName" : "UK", "Age" : 22 }, { "CountryName" : "US", "Age" : 21 } ], "Price" : 178, "Name" : "Chris", "Id" : "NewIdAppped" }Advertisements