在单个查询中同时统计外部和内部嵌入式数组 [英] Count Both Outer and Inner embedded array in a single query
问题描述
{
_id: ObjectId("5dbdacc28cffef0b94580dbd"),
"comments" : [
{
"_id" : ObjectId("5dbdacc78cffef0b94580dbf"),
"replies" : [
{
"_id" : ObjectId("5dbdacd78cffef0b94580dc0")
},
]
},
]
}
如何计算comments
中元素的数量并求和与relies
How to count the number of element in comments
and sum with number of relies
我的方法是像这样进行2次查询:
My approach is do 2 query like this:
db.posts.aggregate([
{$match: {_id:ObjectId("5dbdacc28cffef0b94580dbd")}},
{ $unwind: "$comments",},
{$project:{total:{$size:"$comments.replies"} , _id: 0} }
])
2.计算评论的总数
db.posts.aggregate([
{$match: {_id:ObjectId("5dbdacc28cffef0b94580dbd")}},
{$project:{total:{$size:"$comments.replies"} , _id: 0} }
])
然后对两者进行总结,我们有没有更好的解决方案来编写查询,例如返回总元素comments
+ replies
Then sum up both, do we have any better solution to write the query like return the sum of of total element comments
+ replies
推荐答案
您可以使用 $concatArrays
合并" 内部的数组数组"到单个列表中,并测量 $add
:
You can use $reduce
and $concatArrays
to "merge" an inner "array of arrays" into a single list and measure the $size
of that. Then simply $add
the two results together:
db.posts.aggregate([
{ "$match": { _id:ObjectId("5dbdacc28cffef0b94580dbd") } },
{ "$addFields": {
"totalBoth": {
"$add": [
{ "$size": "$comments" },
{ "$size": {
"$reduce": {
"input": "$comments.replies",
"initialValue": [],
"in": {
"$concatArrays": [ "$$value", "$$this" ]
}
}
}}
]
}
}}
])
请注意,数组数组"是像$comments.replies
这样的表达式的作用,因此需要将它们制作成一个可以测量所有元素的数组的操作.
Noting that an "array of arrays" is the effect of an expression like $comments.replies
, so hence the operation to make these into a single array where you can measure all elements.
这篇关于在单个查询中同时统计外部和内部嵌入式数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!