Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 计数数组中的子文档总数_Mongodb_Mongoose_Aggregation Framework - Fatal编程技术网

Mongodb 计数数组中的子文档总数

Mongodb 计数数组中的子文档总数,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我想要数组中的子文档计数,如果可能,不使用$unwind和$group [{ "_id" : ObjectId("5aefead0227bc943df3fedff"), "doc" : [ { "_id" : ObjectId("5af0e877227bc943df401337"), "shared_with" : [ { "user_id"

我想要数组中的子文档计数,如果可能,不使用
$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`
}]
您可以先尝试聚合,在
doc
上循环,找到
shared\u with
数组的值,然后使用聚合对所有
shared\u进行计数

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
  }
]
您可以使用来统计内部子文档

差不多

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