简体   繁体   English

Golang:MongoDB - 计算投影中嵌套数组的长度

[英]Golang: MongoDB - count length of nested arrays in Projection

In MongoDB i like to count all length of nested arrays togehter.在 MongoDB 中,我喜欢计算嵌套数组的所有长度。 It is just one mongoDB document.它只是一个 mongoDB 文档。

idForDB := "621101966rf42c24a8f41b87"
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 20)
defer cancel()
options := options.FindOneOptions{
        Projection: bson.M{
            "test":          "$test",
            "count": bson.M{}, // count should placed here
        },
    }
result := clients.MongoClient.Database("somedb").Collection("somecollection").FindOne(ctx, bson.M{"_id": idForDB}, &options)

All objects under number are to be counted编号下的所有物体都将被计算在内

{
   "test":"other",
   "list":[
      {
        "number":[
            {
                "value": "1"
            }, 
            {
                "value": "2"
            },
            {
                "value": "2"
            }
        ]
      },
      {
        "number":[
            {
                "value": "1"
            }, 
            {
                "value": "2"
            },
            {
                "value": "2"
            }
        ]
      },
      {
        "number":[
            {
                "value": "1"
            }, 
            {
                "value": "2"
            }
        ]
      }
   ]
}

The output for the "Number" field should be 8 because there are 8 documents under the "number" object. “数字”字段的输出应该是 8,因为“数字”对象下有 8 个文档。

Using mongoDB syntax, you can use $reduce for it:使用 mongoDB 语法,您可以使用$reduce

db.collection.aggregate([
  {$project: {
      test: "$test",
      count: {
        $reduce: {
          input: "$list",
          initialValue: 0,
          in: {$add: ["$$value", {$size: "$$this.number"}]}
        }
      }
    }
  }
])

See how it works on the playground example看看它在操场上的例子是如何工作的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM