Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose distinct select but whole object

Using Mongoose in Node.js. I have this model structure in MongoDB:

{
   "_id":"5ac17dc27707e91ed00cea7d",
   "appid":123,
   "name":"Stellaris",
   "code":"xxxxxxxxxxx"
}

I need to select all items BUT when there is more items of same appid, select just ONE or each appid. Distinct return just array of one field. How select whole objects instead where items with same appid are only once?

like image 679
Baterka Avatar asked Oct 15 '25 21:10

Baterka


1 Answers

Try this

db.getCollection('Collection').aggregate([{
    $group: {
        _id: '$appid',
        "docs": {
            $first: {
                "name": "$name",
                "code": "$code"
            }
        }
    }
}])

OR If you don't want docs field.

db.getCollection('Collection').aggregate([{
    $group: {
        _id: '$appid',
        "name": {
            $first: "$name"
        },
        "code": {
            $first: "$code"
        }
    }
}])
like image 197
Rahul Sharma Avatar answered Oct 18 '25 10:10

Rahul Sharma