【问题标题】:Return object of multiple counts返回多个计数的对象
【发布时间】:2017-03-10 05:45:53
【问题描述】:

我正在尝试查询一个文档并返回一个对象,该对象在一个键中列出了 3 个不同场景的三个计数。集合的组织方式如下:

{
  response_main:{
    type: Schema.ObjectId,
    ref: "topics"
  },
  response_in: {
    type: Number
  }
}

response_in键需要排序是0,1还是2。我目前解决这个问题的方法是:

Collection.aggregate([
  {$match: {response_main: mainTopic._id}},
  {$group: {
    _id: {
      $cond: {if: {$eq: ["$response_in", 0]}, then: "agree", else:{
        $cond: {if: {$eq: ["$response_in", 1]}, then: "neutral", else:{
          $cond: {if: {$eq: ["$response_in", 2]}, then: "disagree", else:false}
        }
      }
    }, count: {$sum: 1}
  }}
], callback);

返回数据的格式是一个对象数组,如下所示:

[
  {
    "_id": "agree",
    "count": 14
  },
  {
    "_id": "neutral",
    "count": 12
  },
  {
    "_id": "disagree",
    "count": 16
  }
]

但是,我希望返回的对象看起来像这样:

{
  "agree": 14,
  "neutral": 12,
  "disagree": 16,
}

我是否可以通过另一种方式来构建查询以实现更简洁的结果?

【问题讨论】:

  • 我建议您回答自己的问题或删除问题。

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

在发送 JSON 响应之前重新格式化数据,现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2013-06-03
    • 2018-10-20
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多