MongoDB $lookup在另一个表中,具有lookup文档中的GroupBy计数字段

jtw3ybtb  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(106)

我尝试在mongoose中使用聚合查找,但我是MongoDB的新手
我有两个不同的 Mongoose 收集如下:

db={
  "options": [
    {
      "_id": "1",
      "name": "A",
      "poll": "123"
    },
    {
      "_id": "2",
      "name": "B",
      "poll": "123"
    },
    {
      "_id": "3",
      "name": "C",
      "poll": "123"
    }
  ],
  "votes": [
    {
      "_id": "1",
      "option": "1"
    },
    {
      "_id": "2",
      "option": "1"
    },
    {
      "_id": "3",
      "option": "3"
    },
    {
      "_id": "4",
      "option": "3"
    },
    {
      "_id": "5",
      "option": "1"
    }
  ]
}

字符串
如果你有类似的经历,能帮我解决这个问题吗?
我想从使用聚合的查询中得到以下格式:

[
  {
    "_id": "1",
    "name": "A",
    "totalVotes": 3,
    "votePercentage": "35"
  },
  {
    "_id": "3",
    "name": "C",
    "totalVotes": 2,
    "votePercentage": "25"
  },
  {
    "_id": "2",
    "name": "B",
    "totalVotes": 0,
    "votePercentage": "0"
  }
]

f0brbegy

f0brbegy1#

这里有两个聚合管道解决方案,请选择任何一个。
解决方案1.

db.options.aggregate([
  {
    '$lookup': {
      'from': 'votes', 
      'localField': '_id', 
      'foreignField': 'option', 
      'as': 'options'
    }
  }, {
    '$project': {
      '_id': '$_id', 
      'name': '$name', 
      'totalVotes': {
        '$size': '$options'
      }
    }
  }, {
    '$addFields': {
      'votePercentage': {
        '$cond': {
          'if': {
            '$eq': [
              '$totalVotes', 0
            ]
          }, 
          'then': '0', 
          'else': '?'
        }
      }
    }
  }
])

字符串
解决方案2.

db.options.aggregate([
  {
    $lookup: {
      from: "votes",
      localField: "_id",
      foreignField: "option",
      as: "options",
    },
  },
  {
    $project: {
      _id: "$_id",
      name: "$name",
      totalVotes: {
        $size: "$options",
      },
      votePercentage: {
        $let: {
          vars: {
            totalVotes: {
              $size: "$options",
            },
          },
          in: {
            $cond: {
              if: {
                $eq: ["$$totalVotes", 0],
              },
              then: "0",
              else: "?",
            },
          },
        },
      },
    },
  },
])


流水线输出:

[
  { _id: '1', name: 'A', totalVotes: 3, votePercentage: '?' },
  { _id: '2', name: 'B', totalVotes: 0, votePercentage: '0' },
  { _id: '3', name: 'C', totalVotes: 2, votePercentage: '?' }
]

相关问题