Mongodb 对单个查询中的外部和内部嵌入数组进行计数
如何计算Mongodb 对单个查询中的外部和内部嵌入数组进行计数,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,如何计算注释中的元素数并与依赖的元素数求和 我的方法是这样做2查询: 1.回复的总元素数 2.计算注释的总元素数 然后总结这两个问题,我们有没有更好的解决方案来编写查询,比如返回元素总数注释+回复尝试使用$unwind将从$project中得到的列表展平,然后再使用$count使用并“合并”一个内部项目将“数组数组”合并到一个列表中,并测量该列表的大小。然后将两个结果简单地组合在一起: db.posts.aggregate([ {$match: {_id:ObjectId("5dbdacc28c
注释中的元素数
并与依赖的元素数求和
我的方法是这样做2查询:
1.回复的总元素数
2.计算注释的总元素数
然后总结这两个问题,我们有没有更好的解决方案来编写查询,比如返回元素总数
注释
+回复
尝试使用$unwind
将从$project
中得到的列表展平,然后再使用$count
使用并“合并”一个内部项目将“数组数组”合并到一个列表中,并测量该列表的大小。然后将两个结果简单地组合在一起:
db.posts.aggregate([
{$match: {_id:ObjectId("5dbdacc28cffef0b94580dbd")}},
{$project:{total:{$size:"$comments.replies"} , _id: 0} }
])
请注意,“数组数组”是类似于
$comments.repress
的表达式的效果,因此需要将这些数组设置为一个数组,在该数组中可以测量所有元素。这是获得结果的另一种方法
输入文件:
db.posts.aggregate([
{ "$match": { _id:ObjectId("5dbdacc28cffef0b94580dbd") } },
{ "$addFields": {
"totalBoth": {
"$add": [
{ "$size": "$comments" },
{ "$size": {
"$reduce": {
"input": "$comments.replies",
"initialValue": [],
"in": {
"$concatArrays": [ "$$value", "$$this" ]
}
}
}}
]
}
}}
])
查询:
{ "_id" : 1, "array1" : [ { "array2" : [ { id: "This is a test!"}, { id: "test1" } ] }, { "array2" : [ { id: "This is 2222!"}, { id: "test 222" }, { id: "222222" } ] } ] }
{ "_id" : 2, "array1" : [ { "array2" : [ { id: "aaaa" }, { id: "bbbb" } ] } ] }
输出:
db.arrsizes2.aggregate( [
{ $facet: {
array1Sizes: [
{ $project: { array1Size: { $size: "$array1" } } }
],
array2Sizes: [
{ $unwind: "$array1" },
{ $project: { array2Size: { $size: "$array1.array2" } } },
],
} },
{ $project: { result: { $concatArrays: [ "$array1Sizes", "$array2Sizes" ] } } },
{ $unwind: "$result" },
{ $group: { _id: "$result._id", total1: { $sum: "$result.array1Size" }, total2: { $sum: "$result.array2Size" } } },
{ $addFields: { total: { $add: [ "$total1", "$total2" ] } } },
] )
更改您的问题标题以更好地反映您所问的内容。您最初的问题标题选择有点接近于长期存在的问题和答案。
{ "_id" : 1, "array1" : [ { "array2" : [ { id: "This is a test!"}, { id: "test1" } ] }, { "array2" : [ { id: "This is 2222!"}, { id: "test 222" }, { id: "222222" } ] } ] }
{ "_id" : 2, "array1" : [ { "array2" : [ { id: "aaaa" }, { id: "bbbb" } ] } ] }
db.arrsizes2.aggregate( [
{ $facet: {
array1Sizes: [
{ $project: { array1Size: { $size: "$array1" } } }
],
array2Sizes: [
{ $unwind: "$array1" },
{ $project: { array2Size: { $size: "$array1.array2" } } },
],
} },
{ $project: { result: { $concatArrays: [ "$array1Sizes", "$array2Sizes" ] } } },
{ $unwind: "$result" },
{ $group: { _id: "$result._id", total1: { $sum: "$result.array1Size" }, total2: { $sum: "$result.array2Size" } } },
{ $addFields: { total: { $add: [ "$total1", "$total2" ] } } },
] )
{ "_id" : 2, "total1" : 1, "total2" : 2, "total" : 3 }
{ "_id" : 1, "total1" : 2, "total2" : 5, "total" : 7 }