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,
}
有沒有另一種方法可以構建我的查詢來實現這個更簡潔的結果?
我會建議你回答自己的問題或刪除問題。 –