英文:
Golang: MongoDB - count length of nested arrays in Projection
问题
在MongoDB中,我喜欢将所有嵌套数组的长度加在一起进行计数。
这只是一个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应该放在这里
},
}
result := clients.MongoClient.Database("somedb").Collection("somecollection").FindOne(ctx, bson.M{"_id": idForDB}, &options)
所有在"number"下的对象都要被计数
{
"test":"other",
"list":[
{
"number":[
{
"value": "1"
},
{
"value": "2"
},
{
"value": "2"
}
]
},
{
"number":[
{
"value": "1"
},
{
"value": "2"
},
{
"value": "2"
}
]
},
{
"number":[
{
"value": "1"
},
{
"value": "2"
}
]
}
]
}
"Number"字段的输出应该是8,因为在"number"对象下有8个文档。
英文:
In MongoDB i like to count all length of nested arrays togehter.
It is just one mongoDB document.
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.
答案1
得分: 1
使用MongoDB语法,你可以使用$reduce
来实现:
db.collection.aggregate([
{$project: {
test: "$test",
count: {
$reduce: {
input: "$list",
initialValue: 0,
in: {$add: ["$$value", {$size: "$$this.number"}]}
}
}
}
}
])
在playground example上查看它的工作原理。
英文:
Using mongoDB syntax, you can use $reduce
for it:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论