Home > Enterprise >  How to exclude _id from mongoose result?
How to exclude _id from mongoose result?

Time:12-22

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 :

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

CodePudding user response:

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