问题
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