emil emil - 13 days ago 5
Node.js Question

How to group records by a child document field in mongoose?

Assuming we have following data

* Parent *

{ _id: 10, child: ObjectID(20) }
{ _id: 11, child: ObjectID(21) }
{ _id: 12, child: ObjectID(23) }


* Children *

{ _id: 20, name: 'test-1' }
{ _id: 21, name: 'test-2' }
{ _id: 22, name: 'test-3' }
{ _id: 23, name: 'test-1' }


I would like know what mongoose to use to get following result.

{ _id: 'test-1', count: 2}
{ _id: 'test-2', count: 1}


I am currently using following query, but the _id in the result is always
{ _id: null, count: 3 }

:(

Parent.aggregate([{
$group: {
_id: '$child.name',
count: { $sum: 1 }
}
}])


Any form of help is appreciated.

Answer

It's better way to create one single collections for avoiding two query on two different collections.

First you should find out all distinct child ids from parent collections and assign to it variable as below :

var allChildIds = db.parent.distinct("child")

After that used that child ids in children collection as below :

db.children.aggregate({"$match":{"_id":{"$in":allChildIds}}},{"$group":{"_id":"$name","sum":{"$sum":1}}})
Comments