Home > Net >  Mongo occurance count by column
Mongo occurance count by column

Time:10-24

I have a usecase to find the count of different statues like active, in-active, in-progress, etc,
the documents look like this -

{
    "id": "1"
    "status": "active"
},
{ 
    "id": "2"
    "status": "active"
},
{
  "id": "3"
  "status": "in-active"
},
{
  "id": "4"
  "status": "in-progress"
}

I needed output like -

{
    "active": 2,
    "in-active": 1,
    "in-progress": 1
}

I am referring this answer but, not able to get the expected output -
Mongo count occurrences of each value for a set of documents

My code is as follows -

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();

CodePudding user response:

  • The first stage is correct
  • $group by null and construct the array of key and value format
  • $arrayToObject convert above converted key-value pair array to an object
  • $replaceRoot to replace above object to root
let result = await collection.aggregate([
  {
    $group: {
      _id: "$status",
      sum: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: null,
      status: {
        $push: { k: "$_id", v: "$sum" }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: { $arrayToObject: "$status" }
    }
  }
])

Playground

  • Related