MongoDB count by referenced document property

让人想犯罪 __ 提交于 2021-02-19 08:26:22

问题


db.foos

{
    bar: ObjectId('123')
}

db.bars

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

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.


回答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
}


来源:https://stackoverflow.com/questions/44562918/mongodb-count-by-referenced-document-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!