Mongoose return filtered result

Viewed 60

I am using mongo db to store some data. My model looks like this:

const ItemSchema = mongoose.Schema({
  name: {
    type: String,
  },
  price: {
    type: Number,
  },})

Lets say i have multiple items with name "Test" and different price and one item with name "Test2"

[{name:"Test", price: 20},{name:"Test", price: 10},{name:"Test", price: 5},{name:"Test2", price: 50}]

How can i get result from database that returns name and lowest price for each item name.

The only thing that comes to my mind is to do something like this

Item.find((err,res)=>{
 //Loop through items with forEach or map
 //res.map((item)=> ...
})

Is there a better way to do this ?

3 Answers

Try this -

Item.aggregate(
    [
        {
            $group:
                {
                    _id: "$name",
                    lowestPrice: { $min: "$price" }
                }
        }
    ]
)

See min aggregator

You can try this

Item.find((err,res)=>{
 //response
}).sort({'price': -1});

Try this:

db.getCollection('test').aggregate( 
[{ 
    $group : { 
        _id : "$name",
        price:{$min:"$price"} 
    }
}])
Related