Pramod Kharade
Pramod Kharade

Reputation: 2085

return match record of array value and group by other property in Mongoose?

we are using mongoDB NoSQl database with NPM library Mongoose and Nodejs.

I have collection called "USERS" and having document format like below:

{user_number: 12, region:"Pune"},
{user_number: 13, region:"Mumbai"},
{user_number: 14, region:"Mumbai"},
{user_number: 15, region:"Punjab"},
{user_number: 16, region:"Delhi"},
{user_number: 17, region:"Pune"}

I am having array of user_Number=[12,13,14,15] so I would like to return matching record of user_number with group by region. User_number array is dynamic.

Expected output is :

{"data":{
 {
            "_id": {
                "region": "pune"
            },
            "count": 1,
            "region": "Pune"
        },
        {
            "_id": {
                "region": "Mumbai"
            },
            "count": 2,
            "region": "Mumbai"
        },
        {
            "_id": {
                "region": "Punjab"
            },
            "count": 1,
            "region": "Punjab"
        },
      }
}

Could you please someone guide me with best approach ?

Thanks in Advance!

Upvotes: 2

Views: 51

Answers (1)

eol
eol

Reputation: 24565

You can use $match and $group in your aggeration pipeline to do this:

db.collection.aggregate([
  {
    "$match": {
      user_number: {
        $in: [12,13,14,15]
      }
    }
  },
  {
    $group: {
      _id: "$region",
      count: {
        $sum: 1
      }
    }
  }
])

You can try this on mongoplayground: https://mongoplayground.net/p/tXpwtngnU1B

Upvotes: 2

Related Questions