如何通过mongoose中的子文档字段对logging进行分组?
假设我们有以下数据
*家长*
{ _id: 10, child: ObjectID(20) } { _id: 11, child: ObjectID(21) } { _id: 12, child: ObjectID(23) }
*儿童*
{ _id: 20, name: 'test-1' } { _id: 21, name: 'test-2' } { _id: 22, name: 'test-3' } { _id: 23, name: 'test-1' }
我想知道用什么mongoose得到下面的结果。
{ _id: 'test-1', count: 2} { _id: 'test-2', count: 1}
我目前正在使用以下查询,但结果中的_id总是{ _id: null, count: 3 }
🙁
Parent.aggregate([{ $group: { _id: '$child.name', count: { $sum: 1 } } }])
任何forms的帮助表示赞赏。
创build单个集合避免两个不同集合上的两个查询是更好的方法。
首先,您应该从父集合中找出所有不同的子ID,并将其分配给它,如下所示:
var allChildIds = db.parent.distinct("child")
之后,在children
收集中使用这个孩子ID如下:
db.children.aggregate({"$match":{"_id":{"$in":allChildIds}}},{"$group":{"_id":"$name","sum":{"$sum":1}}})