本文介绍了MongoDB按引用的文档属性计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

db.foos

{
    bar: ObjectId('123')
}

db.bars

{
    _id: ObjectId('123')
    type: 'wine'
}

如何以最简单的方式找到引用葡萄酒"类型的bar文档的foo文档数量?希望即使集合中包含大量文档,也可以进行缩放以使其表现良好.

How can I in the simplest way find the number of foo-documents that refers to a bar-document of type 'wine'? Hopefully one that scales to perform fairly well even if the collections should contain a very large number of documents.

推荐答案

尝试以下聚合框架查询:

Try this aggregation framework query:

db.foos.aggregate([
   {$lookup:
     {
       from: "bars",
       localField: "_id",
       foreignField: "_id",
       as: "docs"
     }
   },
   {$unwind: "$docs"},
   {$match: {"docs.type":"wine"}},
   {$group: {"_id":"$_id", count: {$sum:1}}}
]
)

我在这些文档上对其进行了测试:

I tested it on these documents:

db.foos.insert({"_id":"123"})
db.foos.insert({"_id":"456"})

db.bars.insert({"_id":"123", type:"wine"})
db.bars.insert({"_id":"456", type:"beer"})

对于葡萄酒类型,我得到的结果是:

and for wine type I get as result:

{
    "_id" : "123",
    "count" : 1
}

这篇关于MongoDB按引用的文档属性计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:04