henit
henit

Reputation: 1180

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.

Upvotes: 1

Views: 905

Answers (1)

Davis Molinari
Davis Molinari

Reputation: 761

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
}

Upvotes: 1

Related Questions