How to join collection in in mongodb? -
i have 3 collections:
collection1 like:
{ "_id" : objectid("5716617f4af77ca97a9614bd"), "count" : 1, "author" : "tony" } { "_id" : objectid("5716617f4af77ca97a9614be"), "count" : 2, "author" : "joe"} { "_id" : objectid("5716617f4af77ca97a9614bf"), "count" : 3, "author" : "mary" } { "_id" : objectid("5716617f4af77ca97a9314bf"), "count" : 2, "author" : "lee" }
means author tony writes 1 book, author joe writes 2 books , author mary writes write 3 books.
collection2 like:
{ "_id" : objectid("5716617f4af77ca97a9614bd"), "count" : 2, "author" : "tony" } { "_id" : objectid("5716617f4af77ca97a9614be"), "count" : 2, "author" : "joe"}
means author tony writes 2 papers, author joe writes 2 papers collection3 like:
{ "_id" : objectid("5716617f4af77ca97a9614bd"), "author" : "tony" } { "_id" : objectid("5716617f4af77ca97a9614be"), "author" : "joe"} { "_id" : objectid("5716617f4af77ca97a9624be"), "author" : "mary"}
i hope author appear in collection3 , sort these authors number of works: result like:
author number: joe 2 + 2 = 4 tony 1 + 2 = 3 mary 3 + 0 = 3
how can write single query finish in mongodb?
this work in 3.2 , above.
db.books.aggregate([{ $lookup: { from: "papers", localfield: "author", foreignfield: "author", as: "papers" } }, { $unwind: "$papers" }, { $group: { _id: "$author", bookcount: {$sum: "$count"}, paperscount: {$sum: "$papers.count"}, } }, { $project: { _id: 0, author: "$_id", total: { $add: [ "$bookcount", "$paperscount"] } } }])
outputs:
/* 1 */ { "author" : "tony", "total" : 3 } /* 2 */ { "author" : "joe", "total" : 4 }
Comments
Post a Comment