Monta
Monta

Reputation: 1180

Mongodb group embedded objects

I have this collection:

{
"_id" : "1",
"productGroup" : "G1",
"product" : {
    "oldPrice" : 1.22,
    "newPrice" : 1.33
    }
},
{
"_id" : "2",
"productGroup" : "G1",
"product" : {
     "oldPrice" : 1.12,
     "newPrice" : 1.23
    }
}

I want to group by productGroup and keep only the product having min newPrice In my case it would be

{
"_id" : "G1",
"product" : {
   "oldPrice" : 1.12,
   "newPrice" : 1.23
   }
}

If I do this, I get only the newPrice property included while I need the whole product embedded object

db.myColl.aggregate([{
    "$group" : {
        _id : "$productGroup",
        product : { "$min" : "$product.newPrice"}
    }
}])

Any idea on how to do it?

Upvotes: 0

Views: 57

Answers (1)

Clement Amarnath
Clement Amarnath

Reputation: 5466

In the aggregation pipeline use $sort and $first to get the desired result of getting the minimum new price in each group.

db.myColl.aggregate([
    {$sort: {"product.newPrice":1}},
    {$group: {_id:"$productGroup", product:{$first:"$product"}}}
]);

Upvotes: 1

Related Questions