在单个查询中同时统计外部和内部嵌入式数组 [英] Count Both Outer and Inner embedded array in a single query

查看:53
本文介绍了在单个查询中同时统计外部和内部嵌入式数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆