MongoDB按引用的文档属性计数

时间:2017-06-15 08:48:22

标签: mongodb count aggregation-framework

db.foos

{
    bar: ObjectId('123')
}

db.bars

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

我怎样才能以最简单的方式找到引用'wine'类型的条形文档的foo文档的数量?希望即使集合中应包含大量文档,也可以进行相当好的扩展。

1 个答案:

答案 0 :(得分:1)

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
}