对于类似于UNION两个集合的查询,请在MongoDB中将JOIN与一起使用aggregate()
。让我们创建一个包含文档的集合-
> 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 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo486.find();
这将产生以下输出-
{ "_id" : 1, "Amount" : 30, "No" : 4 } { "_id" : 2, "Amount" : 40, "No" : 2 } { "_id" : 3, "Amount" : 60, "No" : 6 }
以下是使用文档创建第二个集合的查询-
> 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 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo487.find();
这将产生以下输出-
{ "_id" : 1, "Price" : 10, "No" : 4 } { "_id" : 2, "Price" : 80, "No" : 9 } { "_id" : 3, "Price" : 20, "No" : 6 }
以下是在MongoDB中对UNION的两个查询-
> 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 ... } ... } ... ])
这将产生以下输出-
{ "TotalValue" : 40, "No" : 4 } { "TotalValue" : 80, "No" : 6 }