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

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

问题描述

<代码>{_id: ObjectId("5dbdacc28cffef0b94580dbd"),评论" : [{"_id" : ObjectId("5dbdacc78cffef0b94580dbf"),回复":[{"_id" : ObjectId("5dbdacd78cffef0b94580dc0")},]},]}

如何统计comments中的元素个数并与relies

的个数相加

我的方法是做 2 个这样的查询:

1.回复

的总元素

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 + reply

解决方案

您可以使用 $reduce$concatArrays合并"一个内部的数组数组"到一个列表中并测量$size 其中.然后只需 $add 两个结果一起:

db.posts.aggregate([{ "$match": { _id:ObjectId("5dbdacc28cffef0b94580dbd") } },{$addFields":{totalBoth":{"$add": [{ "$size": "$comments" },{$size":{$减少":{"input": "$comments.replys",初始值": [],在": {"$concatArrays": [ "$$value", "$$this"]}}}}]}}}])

请注意,数组数组"是像 $comments.replies 这样的表达式的结果,因此操作将它们组合成一个可以测量所有元素的数组.

{
_id: ObjectId("5dbdacc28cffef0b94580dbd"),
 "comments" : [
     {
      "_id" : ObjectId("5dbdacc78cffef0b94580dbf"),
      "replies" : [
                   {
                     "_id" : ObjectId("5dbdacd78cffef0b94580dc0")          
                   },
                 ]
     },
  ]
}

How to count the number of element in comments and sum with number of relies

My approach is do 2 query like this:

1. total elements of replies

db.posts.aggregate([
{$match: {_id:ObjectId("5dbdacc28cffef0b94580dbd")}},

{ $unwind: "$comments",},

{$project:{total:{$size:"$comments.replies"} , _id: 0} }

])

2. count total elements of comments

db.posts.aggregate([
{$match: {_id:ObjectId("5dbdacc28cffef0b94580dbd")}},
{$project:{total:{$size:"$comments.replies"} , _id: 0} }

])

Then sum up both, do we have any better solution to write the query like return the sum of of total element comments + replies

解决方案

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" ] 
            }
          }
        }}
      ]
    }
  }}
])

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天全站免登陆