Mongoose - How to exclude _id from the result

Viewed 68

I am getting an issue getting 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 :

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 an error.

1 Answers

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

Related