【问题标题】:mongodb - How to get two counts from one query without putting them in an array [duplicate]mongodb - 如何从一个查询中获取两个计数而不将它们放入数组中[重复]
【发布时间】:2020-08-08 22:46:02
【问题描述】:

我有一个 cmets 集合,其中包含两个字段 - “up”和“down”。现在,我只使用其中一个来使用下面的查询来获取计数:

              $lookup: {
            from: "votesComments",
            as: "commentVotes",
            let: {
              commentI: "$_id"
            },
            pipeline: [
              {
                $match: {
                  $expr: {
                    $eq: [
                      "$commentId",
                      "$$commentI"
                    ]
                  },
                  }
                },
                {
                  "$group" : {_id:"$up", count:{$sum:1}}
                },
                
              ]
            }                

          },

结果是:

0: {_id: 1, count: 2}  ====>  id = 1 is when "up" field has 1. Total up votes is 2
1: {_id: 0, count: 1}  ====>  id = 0 is when "up" field has 0. Total down votes is 1

这是一个数组。当我放松它时,我只会得到

{_id: 1, count: 2}

我需要执行以下操作之一:

  1. 以简单的格式获取结果 - {upvotes: 2, downvotes: 1}
  2. 展开结果以包含结果数组的[0][1] 元素。 或
  3. 是否可以在一个查询中执行两个计数? [计算 Up 字段中 1 的数量和 Down 字段中 1 的数量?

【问题讨论】:

标签: mongodb


【解决方案1】:

做到了

            "$group": {
              "_id": "null",      
              "upCount": { "$sum": "$up" },
              "downCount": { "$sum": "$down" } 
            },

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多