如何在mongodb中加入收藏?

时间:2016-04-19 19:40:14

标签: mongodb

我有3个收藏品:

collection1就像:

{ "_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" }

意味着作者托尼写了一本书,作者乔写了2本书,作者玛丽写了3本书。

collection2就像:

{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "count" : 2, "author" : "Tony" }
{ "_id" : ObjectId("5716617f4af77ca97a9614be"), "count" : 2, "author" : "Joe"}

意味着作者托尼写了2篇论文,作者乔写了2篇论文 Collection3就像:

{ "_id" : ObjectId("5716617f4af77ca97a9614bd"),  "author" : "Tony" }
{ "_id" : ObjectId("5716617f4af77ca97a9614be"),  "author" : "Joe"}
{ "_id" : ObjectId("5716617f4af77ca97a9624be"),  "author" : "Mary"}

我希望让作者出现在collection3中并根据作品的数量对这些作者进行排序: 结果如下:

author    number:
Joe        2 + 2 = 4
Tony       1 + 2 = 3
Mary       3 + 0 = 3

如何在mongodb中编写单个查询来完成此操作?

1 个答案:

答案 0 :(得分:0)

这只适用于3.2及以上版本。

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"] }
    }
}])

输出:

/* 1 */
{
    "author" : "Tony",
    "total" : 3
}

/* 2 */
{
    "author" : "Joe",
    "total" : 4
}