MongoDB count by referenced document property
问题 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":