Asef Pourmasoomi
Asef Pourmasoomi

Reputation: 514

How get the document with minimum value in MongoDB?

I have some documents like these:

{ "_id" : 1, "type" : "A", "price" : 10, "name" : "A1"}
{ "_id" : 2, "type" : "A", "price" : 30, "name" : "A2"}
{ "_id" : 3, "type" : "A", "price" : 20, "name" : "A3"}
{ "_id" : 4, "type" : "B", "price" : 15, "name" : "B1"}
{ "_id" : 5, "type" : "B", "price" : 25, "name" : "B2"}
{ "_id" : 6, "type" : "B", "price" : 5, "name" : "B3"}
{ "_id" : 7, "type" : "C", "price" : 30, "name" : "C1"}
{ "_id" : 8, "type" : "C", "price" : 20, "name" : "C2"}

I want to find the document (whole fields including "name") with minimum price value per each "type", like as:

{ "type" : "A", "price" : 10, "name" : "A1"}
{ "type" : "B", "price" : 5, "name" : "B3"}
{ "type" : "C", "price" : 20, "name" : "C2"}

Is there any idea how I can write a MongoDB query? Thanks

Upvotes: 1

Views: 1726

Answers (2)

Prakash Harvani
Prakash Harvani

Reputation: 1041

Instead You can try this.

 db.collection.aggregate([
     {
       $group:
         {
           _id: "$type",
            name: { $first: "$name" },
           price: { $min: "$price" }
         }
     }
   ])

Upvotes: -1

turivishal
turivishal

Reputation: 36154

You can use $sort before $group,

  • $sort by price ascending order
  • $group by type and add first record in all fields
db.collection.aggregate([
  { $sort: { price: 1 } },
  {
    $group: {
      _id: "$type",
      name: { $first: "$name" },
      price: { $first: "$price" }
    }
  }
])

Playground

Upvotes: 2

Related Questions