Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclude _id from mongoose result?

I am getting issue to get the desired output like this

    [
        {
            
             "status": "ONBOARD"
              "count": 1
        },
       {
            
             "status": "PENDING"
              "count": 1
        },
        
    ]

I am getting like this:

[
    {
        "_id": {
            "status": "ONBOARD"
        },
        "count": 1
    },
    {
        "_id": {
            "status": "CLIENT_ROUND"
        },
        "count": 2
    },
    {
        "_id": {
            "status": "SCREENED"
        },
        "count": 1
    }
]

here is my aggregate :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result = await Lead.aggregate([

      {
        $group: {
          _id: { status: '$status' },
          count: { $sum: 1 }
        }
        $project: { _id: 0, status: 1, count: 1 }
      }

Help me to get the output I am new i have applied $project but giving me error

>Solution :

You’re almost there. With status: "$_id.status" in the projection stage.

db.collection.aggregate([
  {
    $group: {
      _id: {
        status: "$status"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      status: "$_id.status",
      count: 1
    }
  }
])

Sample Mongo Playground


Or just $group with _id: "$status".

db.collection.aggregate([
  {
    $group: {
      _id: "$status",
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      status: "$_id",
      count: 1
    }
  }
])

Sample Mongo Playground 2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading