通过MongoDB聚合管道中的字段值识别子组

时间:2019-08-25 01:27:58

标签: mongodb aggregation-framework

我正在尝试使用MongoDB聚合管道在称为链接的模型上生成票数。

我的投票模型有一个“ linkID”字段和一个“喜欢的”字段,该字段是正在投票的链接的外键,该字段是1或0,表示正面或负面的投票。我想返回的是每个链接的文档,该文档具有名为“ yesVotes”的字段,其投票总数为“喜欢”值为1,而“ noVotes”的投票总数为0。

目前,我有:

Vote.aggregate([
{ $group:
  {
    _id: {link: "$linkID", rating: "$liked"},
    count: { $sum: 1 }
  }
},
{ $group:
  {
    _id: "$_id.link",
    votes: {
      $addToSet: { rating: "$_id.rating", count: "$count"}
    }
  }
}
]);

为每个链接返回类似的内容:

  {
    "_id": "5d464628908dbf00072daa11",
    "votes": [
      {
        "rating": 0,
        "count": 1
      },
      {
        "rating": 1,
        "count": 2
      }
    ]
  }

但是,这不会区分是赞成票和反对票,也不会以未定义的顺序返回它们。我可以对它们进行排序,但不能保证任何单个链接上都可以通过投票。

如何返回分别具有值为0或1的票数的字段?

1 个答案:

答案 0 :(得分:0)

想通了!可以使用$cond以更简单的方式做到这一点:

Vote.aggregate([
  { $group:
    {
      _id: { link: "$linkID" },
      yesVotes: { $sum: { $cond: { if: { $eq: ["$liked", 1] }, then: 1, else: 0 }}},
      noVotes: { $sum: { $cond: { if: { $eq: ["$liked", 0] }, then: 1, else: 0 }}}
    }
  }
]);

这将返回:

  {
    "_id": {
      "link": "5d5b30fa4d607f0007715683"
    },
    "yesVotes": 3,
    "noVotes": 0
  },