【问题标题】:MongoDB. Aggregate the sum of two arrays sizesMongoDB。聚合两个数组大小的总和
【发布时间】:2018-06-03 00:23:10
【问题描述】:

使用 MongoDB 3.4.10 和 mongoose 4.13.6,我可以计算用户模型上两个数组的大小:

User.aggregate()
  .project({
    '_id': 1,
    'leftVotesCount': { '$size': '$leftVoted' },
    'rightVotesCount': { '$size': '$rightVoted' }
  })

我的用户在哪里(db.users.find()

{ "_id" : ObjectId("5a2b21e63023c6117085c240"), "rightVoted" : [ 2 ], “左投票”:[1, 6] }

{ "_id" : ObjectId("5a2c0d68efde3416​​bc8b7020"), "rightVoted" : [ 2 ], “左投票”:[1]}

我得到了预期的结果:

[ { _id: '5a2b21e63023c6117085c240', leftVotesCount: 2, rightVotesCount: 1 },

{ _id: '5a2c0d68efde3416​​bc8b7020', leftVotesCount: 1, rightVotesCount: 1 } ]

问题。如何获得leftVotesCountrightVotesCount 数据的累积值?我尝试了以下操作:

User.aggregate()
  .project({
    '_id': 1,
    'leftVotesCount': { '$size': '$leftVoted' },
    'rightVotesCount': { '$size': '$rightVoted' },
    'votesCount': { '$add': [ '$leftVotesCount', '$rightVotesCount' ] },
    'votesCount2': { '$sum': [ '$leftVotesCount', '$rightVotesCount' ] }
  })

votesCountnullvotesCount20 对于两个用户。我期待用户 1 的 votesCount = 3 和用户 2 的 votesCount = 2

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    $leftVotesCount$rightVotesCount 仅在下一阶段可用。尝试类似:

    User.aggregate()
      .project({
        '_id': 1,
        'leftVotesCount': { '$size': '$leftVoted' },
        'rightVotesCount': { '$size': '$rightVoted' }
      })
      .project({
        '_id': 1,
        'leftVotesCount': 1,
        'rightVotesCount': 1
        'votesCount': { '$add': [ '$leftVotesCount', '$rightVotesCount' ] },
        'votesCount2': { '$sum': [ '$leftVotesCount', '$rightVotesCount' ] }
      })
    

    【讨论】:

    • 感谢您的澄清,我会记下的!同时,我找到了一种方法,无需leftVotesCountrightVotesCount 即可一步获得结果...
    【解决方案2】:

    您不能引用在同一项目阶段创建的项目变量。

    您可以将变量包装在$let 表达式中。

    User.aggregate().project({
      "$let": {
        "vars": {
          "leftVotesCount": {
            "$size": "$leftVoted"
          },
          "rightVotesCount": {
            "$size": "$rightVoted"
          }
        },
        "in": {
          "votesCount": {
            "$add": [
              "$$leftVotesCount",
              "$$rightVotesCount"
            ]
          },
          "leftVotesCount": "$$leftVotesCount",
          "rightVotesCount": "$$rightVotesCount"
        }
      }
    })
    

    【讨论】:

      【解决方案3】:

      原来$add支持嵌套表达式,所以我可以通过排除中间变量来解决这个问题:

      User.aggregate().project({
        '_id': 1,
        'votesCount': { '$add': [ { '$size': '$leftVoted' }, { '$size': '$rightVoted' } ] }
      });
      
      // [ {_id: '...', votesCount: 3}, {_id: '...', votesCount: 2} ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-01
        • 2013-01-12
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        相关资源
        最近更新 更多