【问题标题】:How to count specific sub documents on other sub documents in mongoose?如何计算猫鼬中其他子文档上的特定子文档?
【发布时间】:2020-11-19 23:13:17
【问题描述】:

我有一个这样的结构:

{
    "user" : "admin",
    "exercises" : [
        {
            "name" : "exercise 1",
            "documents" : [
                {
                    "idDoc" : "1",
                    "name" : "doc1"
                },
                {
                    "idDoc" : "2",
                    "name" : "doc1"
                },
                {
                    "idDoc" : "3",
                    "name" : "doc2"
                }
            ]
        }
    ]
}

如何计算名称 = doc1 的所有文档?

输出是:

{
    "_id" : "objectId", --userId
    "count" : 2
}

我知道下面的代码可以计算所有文档,但我不知道用条件来计算它们。

Schema.aggregate()
            .match({ user: username })
            .project({ size: {
                $reduce : {
                    "input" : "$exercises",
                    "initialValue" : 0,
                    "in" : {"$add":["$$value",{"$size":"$$this.documents"}]}
                }
            }});

请帮忙!感谢您的阅读。

【问题讨论】:

    标签: node.js mongoose aggregation-framework


    【解决方案1】:

    使用$reduce 是正确的方法,只需要对数据处理进行一些更改。您可以使用$reduce 和$filter 创建一个数组,其中包含名称为doc1 的所有文档,然后使用$size 计算该数组中的项目。示例:

    db.collection.aggregate([
      { $match: { user: "admin" } },
      {
        $addFields: {
          count: {
            $size: {
              $reduce: {
                input: "$exercises",
                initialValue: [],
                in: {
                  $concatArrays: [
                    "$$value",
                    {
                      $filter: {
                        input: "$$this.documents",
                        as: "item",
                        cond: { $eq: ["$$item.name", "doc1"] }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      },
    ])
    

    MongoPlayground

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2015-06-26
      • 2015-10-01
      相关资源
      最近更新 更多