计算数组中的子文档总数

时间:2018-07-17 06:28:46

标签: mongodb mongoose aggregation-framework

如果可能,我希望不使用$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`
}]

2 个答案:

答案 0 :(得分:2)

您可以先尝试进行$map聚合,以遍历doc并找到shared_with数组的$size,然后将所有shared_with用{ {3}}聚合

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
  }
]

答案 1 :(得分:1)

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

类似

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