MongoDB的。聚合两个数组大小的总和

问题描述 投票:1回答:3

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

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

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

{“_ id”:ObjectId(“5a2b21e63023c6117085c240”),“rightVoted”:[2],“leftVoted”:[1,6]}

{“_ id”:ObjectId(“5a2c0d68efde3416​​bc8b7020”),“rightVoted”:[2],“leftVoted”:[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' ] }
  })

votesCountnullvotesCount2是两个用户的0。我期待用户1的votesCount = 3和用户2的votesCount = 2

mongodb mongoose
3个回答
3
投票

$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' ] }
  })

2
投票

您无法引用在同一项目阶段中创建的项目变量。

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

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

1
投票

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

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

// [ {_id: '...', votesCount: 3}, {_id: '...', votesCount: 2} ]
© www.soinside.com 2019 - 2024. All rights reserved.