【问题标题】:How to group records by a child document field in mongoose?如何在猫鼬中按子文档字段对记录进行分组?
【发布时间】:2016-11-22 04:09:49
【问题描述】:

假设我们有以下数据

* 父级 *

{ _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' }

我想知道用什么猫鼬来获得以下结果。

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

我目前正在使用以下查询,但结果中的 _id 始终为 { _id: null, count: 3 } :(

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

感谢任何形式的帮助。

【问题讨论】:

  • 这是两个不同的集合?
  • 是的,它们是不同的集合@Yogesh
  • 在这种情况下,您应该首先在父集合上编写两个不同的查询,获取所有子 id,并在子集合中使用子集合中的子 id,在聚合 $match 中使用 $in 并按 name 分组,最后sum
  • @Yogesh 您能否详细说明答案?

标签: node.js mongodb mongoose


【解决方案1】:

最好创建一个集合以避免对两个不同集合进行两次查询。

首先,您应该从父集合中找出所有不同的子 ID,并将其分配给如下变量:

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

之后在children 集合中使用了该子 ID,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 2020-07-25
    • 2019-10-30
    • 2015-11-16
    • 2020-07-26
    • 1970-01-01
    • 2023-01-12
    • 2017-06-06
    相关资源
    最近更新 更多