我在 mongodb 中有一個如下所示的模式
let reactions = [
{
messageId: 1,
reactions: [
{
"userid": "7212898122",
"reactionId": 2,
"date": "2022-05-12T18:55:49.943Z"
},
{
"userid": "8171763225",
"reactionId": 2,
"date": "2022-05-12T19:27:34.324Z"
},
{
"userid": "8782323232",
"reactionId": 3,
"date": "2022-05-12T18:55:49.943Z"
}
]
},
{
messageId: 2,
reactions: [
{
"userid": "7212898122",
"reactionId": 1,
"date": "2022-05-12T18:55:49.943Z"
},
{
"userid": "8171763225",
"reactionId": 2,
"date": "2022-05-12T19:27:34.324Z"
},
{
"userid": "8782323232",
"reactionId": 1,
"date": "2022-05-12T18:55:49.943Z"
}
]
}
]
我想要這樣的結果
let result = [
{
messageId:1,
count:{
2:2,
3:1
}
},
{
messageId:1,
count:{
1:2,
2:1
}
}
]
表示兩個用戶對反應 ID 2 作出反應,一個用戶對反應 ID 1 作出反應,與所有 messageId 相同
我嘗試了小組,但并沒有完全得到我想要的結果。請回答。
====================================
uj5u.com熱心網友回復:
您可以執行以下操作:
$unwind分離反應$group通過messageId和reactionId,得到你想要的計數$group通過 messageId 來“還原”并在陣列中$unwind使用kandv以啟用轉換為物件。$project格式化為物件
db.collection.aggregate([
{
$unwind: "$reactions"
},
{
$group: {
_id: {
messageId: "$messageId",
reactionId: "$reactions.reactionId"
},
count: {$sum: 1}
}
},
{
$group: {
_id: "$_id.messageId",
count: {
$push: {k: {$toString: "$_id.reactionId"}, v: "$count"}}
}
},
{
$project: {
messageId: "$_id",
_id: 0,
count: {$arrayToObject: "$count" }
}
}
])
但是在 mongodb 上,鍵應該是字串。
游樂場示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474009.html
標籤:节点.js mongodb mongodb-nodejs-驱动程序
