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
Implement a query similar to MySQL Union with MongoDB?
For a similar query to UNION two collections, use JOIN in MongoDB along with aggregate(). Let us create a collection with documents −
> db.demo486.insertOne({_id:1,"Amount":30,"No":4});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo486.insertOne({_id:2,"Amount":40,"No":2});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo486.insertOne({_id:3,"Amount":60,"No":6});
{ "acknowledged" : true, "insertedId" : 3 }
Display all documents from a collection with the help of find() method −
> db.demo486.find();
This will produce the following output −
{ "_id" : 1, "Amount" : 30, "No" : 4 }
{ "_id" : 2, "Amount" : 40, "No" : 2 }
{ "_id" : 3, "Amount" : 60, "No" : 6 }
Following is the query to create second collection with documents −
> db.demo487.insertOne({_id:1,"Price":10,"No":4});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo487.insertOne({_id:2,"Price":80,"No":9});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo487.insertOne({_id:3,"Price":20,"No":6});
{ "acknowledged" : true, "insertedId" : 3 }
Display all documents from a collection with the help of find() method −
> db.demo487.find();
This will produce the following output −
{ "_id" : 1, "Price" : 10, "No" : 4 }
{ "_id" : 2, "Price" : 80, "No" : 9 }
{ "_id" : 3, "Price" : 20, "No" : 6 }
Following is the query to UNION two queries in MongoDB −
> db.getCollection('demo486').aggregate([
... {$lookup : { from : "demo487",localField : "No", foreignField :"No", as:"demo487"}},
... {$unwind : "$demo487"},
... {
... $group : {
... _id : {
... No :"$No",
... },
... TotalValue : { $sum : { $add: [ "$Amount", "$demo487.Price" ] }}
... }
... },
... {$sort : {"_id.No":1}},
... {
... $project : {
... No :"$_id.No",
... TotalValue : 1,
... _id : 0
... }
... }
... ])
This will produce the following output −
{ "TotalValue" : 40, "No" : 4 }
{ "TotalValue" : 80, "No" : 6 }Advertisements