Implement a query similar to MySQL Union with MongoDB?

MongoDBMySQLDatabaseBig Data Analytics

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 }
raja
Published on 11-May-2020 13:29:51
Advertisements