【问题标题】:count total number sub document in Array计算数组中子文档的总数
【发布时间】:2018-09-12 22:14:38
【问题描述】:

如果可能的话,我希望不使用 $unwind$group 对数组中的子文档进行计数。

[{
    "_id" : ObjectId("5aefead0227bc943df3fedff"),
    "doc" : [ 
        {
            "_id" : ObjectId("5af0e877227bc943df401337"),
            "shared_with" : [ 
                {
                    "user_id" : ObjectId("5ad5e57b473e2606e0d443c3"),
                    "_id" : ObjectId("5af0e877227bc943df401339")
                }, 
                {
                    "user_id" : ObjectId("5adbf029b2da8e380b9321b6"),
                    "_id" : ObjectId("5af0e877227bc943df401338")
                }
            ]
        }, 
        {
            "_id" : ObjectId("5b4d856702d7f52974aab962"),
            "shared_with" : [ 
                {
                    "user_id" : ObjectId("5ac7083ce56c9d304f2fa533"),
                    "_id" : ObjectId("5b4d856702d7f52974aab963")
                }
            ]
        }
    ]
}]

以上是我查找后得到的结果,我想计算包含文档的数组('doc')内的子文档('shared_with')的总数,

所以我想要的输出如下,

[{
   "_id" : ObjectId("5aefead0227bc943df3fedff"),
   "count":3`enter code here`
}]

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以先尝试$map 聚合,循环遍历doc 并找到shared_with 数组的$size,然后用$sum 聚合计算所有shared_with

    db.collection.aggregate([
      { "$project": {
        "doc": {
          "$map": {
            "input": "$doc",
            "as": "do",
            "in": {
              "_id": "$$do._id",
              "count": { "$size": "$$do.shared_with" }
            }
          }
        }
      }},
      { "$project": {
        "count": { "$sum": "$doc.count" }
      }}
    ])
    

    输出

    [
      {
        "_id": ObjectId("5aefead0227bc943df3fedff"),
        "count": 3
      }
    ]
    

    【讨论】:

      【解决方案2】:

      您可以使用$reduce 来计算内部子文档。

      类似

      db.colname.aggregate([
        {"$project":{
          "count":{
            "$reduce":{
              "input":"$doc",
              "initialValue":0,
              "in":{"$add":["$$value",{"$size":"$$this.shared_with"}]}
            }
          }
        }}
      ]) 
      

      【讨论】:

        猜你喜欢
        • 2016-05-12
        • 1970-01-01
        • 2022-01-06
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 2023-04-05
        相关资源
        最近更新 更多