mongodb 按列列出的蒙古语出现计数

2lpgd968  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(122)

我有一个用例,用于查找不同状态(如活动、非活动、进行中等)的计数,
文档看起来像这样-

  1. {
  2. "id": "1"
  3. "status": "active"
  4. },
  5. {
  6. "id": "2"
  7. "status": "active"
  8. },
  9. {
  10. "id": "3"
  11. "status": "in-active"
  12. },
  13. {
  14. "id": "4"
  15. "status": "in-progress"
  16. }

我需要输出像-

  1. {
  2. "active": 2,
  3. "in-active": 1,
  4. "in-progress": 1
  5. }

我指的是这个答案,但无法得到预期的输出-
Mongo count occurrences of each value for a set of documents
我的代码如下-

  1. const mongoClient = require('mongodb').MongoClient;
  2. const test = async () => {
  3. const mongoUri = "mongodb://localhost:27017/";
  4. const dbClientConnection = await mongoClient.connect(mongoUri, {
  5. useNewUrlParser: true,
  6. useUnifiedTopology: true
  7. });
  8. const db = await dbClientConnection.db("database name here");
  9. const collection = await db.collection("collection name here");
  10. let result = await collection.aggregate([
  11. {
  12. $group: {
  13. _id: "$status",
  14. sum: { $sum: 1 }
  15. }
  16. },
  17. {
  18. $group: {
  19. _id: null,
  20. status: {
  21. $push: { k: "$_id", v: "$sum" }
  22. }
  23. }
  24. },
  25. {
  26. $replaceRoot: {
  27. newRoot: { $arrayToObject: "$status" }
  28. }
  29. }
  30. ])
  31. console.log("result => ", result);
  32. return result;
  33. }
  34. test();
q3qa4bjr

q3qa4bjr1#

  • 第一阶段是正确的
  • $group通过null并构造键值格式的数组
  • $arrayToObject将上述转换后的键值对数组转换为对象
  • $replaceRoot将上述对象替换为根
  1. let result = await collection.aggregate([
  2. {
  3. $group: {
  4. _id: "$status",
  5. sum: { $sum: 1 }
  6. }
  7. },
  8. {
  9. $group: {
  10. _id: null,
  11. status: {
  12. $push: { k: "$_id", v: "$sum" }
  13. }
  14. }
  15. },
  16. {
  17. $replaceRoot: {
  18. newRoot: { $arrayToObject: "$status" }
  19. }
  20. }
  21. ])

Playground

展开查看全部

相关问题