我有一个用例,用于查找不同状态(如活动、非活动、进行中等)的计数,
文档看起来像这样-
{
"id": "1"
"status": "active"
},
{
"id": "2"
"status": "active"
},
{
"id": "3"
"status": "in-active"
},
{
"id": "4"
"status": "in-progress"
}
我需要输出像-
{
"active": 2,
"in-active": 1,
"in-progress": 1
}
我指的是这个答案,但无法得到预期的输出-
Mongo count occurrences of each value for a set of documents
我的代码如下-
const mongoClient = require('mongodb').MongoClient;
const test = async () => {
const mongoUri = "mongodb://localhost:27017/";
const dbClientConnection = await mongoClient.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = await dbClientConnection.db("database name here");
const collection = await db.collection("collection name here");
let result = await collection.aggregate([
{
$group: {
_id: "$status",
sum: { $sum: 1 }
}
},
{
$group: {
_id: null,
status: {
$push: { k: "$_id", v: "$sum" }
}
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$status" }
}
}
])
console.log("result => ", result);
return result;
}
test();
1条答案
按热度按时间q3qa4bjr1#
$group
通过null并构造键值格式的数组$arrayToObject
将上述转换后的键值对数组转换为对象$replaceRoot
将上述对象替换为根Playground