0
我在查询文档并返回一个单个对象,该对象列出了三个不同场景中的三个计数。以下是如何收集的组织:多次计数的返回对象
{
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,
}
有没有另一种方法可以构建我的查询来实现这个更简洁的结果?
我会建议你回答自己的问题或删除问题。 –