问题描述
所以我有一堆简单的文档,例如
so i have a bunch of simple documents like
{
"foos": [
ObjectId("5105862f2b5e30877c685c58"),
ObjectId("5105862f2b5e30877c685c57"),
ObjectId("5105862f2b5e30877c685c56"),
],
"typ": "Organisation",
}
,我想找出与组织"类型的文档相关的foos
的总体大小
and i want to find out the overall size of associated foos
to documents of type "Organisation"
所以我有这个汇总查询
db.profil.aggregate(
[
{
$match:{
"typ":"Organisation"
}
},
{
$project: {
fooos: { $size: "$foos" }
}
}
]
)
这将返回每个文档的所有foo的计数
this returns the count of all foos for each document
like:
{ "_id" : ObjectId("50e577602b5e05e74b38a6c8"), "foooos" : 1 }
{ "_id" : ObjectId("51922170975a09f363e3eef5"), "foooos" : 3 }
{ "_id" : ObjectId("51922170975a09f363e3eef8"), "foooos" : 2 }
{ "_id" : ObjectId("5175441d975ae346a3a8dff2"), "foooos" : 0 }
{ "_id" : ObjectId("5192216f975a09f363e3eee9"), "foooos" : 2 }
{ "_id" : ObjectId("5192216f975a09f363e3eeeb"), "foooos" : 3 }
{ "_id" : ObjectId("5192216f975a09f363e3eee4"), "foooos" : 2 }
{ "_id" : ObjectId("5192216f975a09f363e3eee6"), "foooos" : 2 }
{ "_id" : ObjectId("5192216f975a09f363e3eedb"), "foooos" : 2 }
{ "_id" : ObjectId("51922174975a09f363e3ef4a"), "foooos" : 1 }
{ "_id" : ObjectId("5192216f975a09f363e3eee1"), "foooos" : 1 }
{ "_id" : ObjectId("5192216e975a09f363e3eed7"), "foooos" : 2 }
{ "_id" : ObjectId("5192216f975a09f363e3eeee"), "foooos" : 3 }
是否有一些查询可以返回所有文档的foo的总计数?
is there some query that would return the summed up count for foos of all documents ?
我用$ sum玩过,但是不知道如何与查询结合,我只会得到语法错误,知道这是否可行
i played arround with $sum but dont know how to combine with my query, i only do get syntax errors, it would be cool to know if this is possible
推荐答案
包括 $group
操作员流水线阶段,位于 $project
步骤如下:
Include the $group
operator pipeline stage after the $project
step as follows:
db.profil.aggregate([
{ "$match":{ "typ": "Organisation" } },
{ "$project": {
"fooos": { "$size": "$foos" }
} },
{ "$group": {
"_id": null,
"count": {
"$sum": "$fooos"
}
} }
])
这会将先前 $project
阶段并应用累加器表达式fooos字段上的="noreferrer"> $sum
以获取总计(使用上一个示例):
This will group all the input documents from the previous $project
stage and applies the accumulator expression $sum
on the fooos
field within the group to get the total (using your last example):
这也可以通过 $project
管道为:
This can also be done by-passing the $project
pipeline as:
db.profil.aggregate([
{ "$match": { "typ": "Organisation" } },
{ "$group": {
"_id": null,
"count": {
"$sum": { "$size": "$foos" }
}
} }
])
输出
/* 0 */
{
"result" : [
{
"_id" : null,
"count" : 24
}
],
"ok" : 1
}
这篇关于Mongodb求和数组字段的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!