Reputation: 4127
How do you get a document with the minimum or maximum value in a field in MongoDB?
Similar to the MIN() or MAX() functions in MySQL, but using the NodeJS MongoDB driver. Any ideas?
Upvotes: 1
Views: 1876
Reputation: 544
you can try to use asc, desc sort with limit(1)
db.col.insert({val: 9});
db.col.insert({val: 4});
db.col.insert({val: 20});
db.col.find();
{ "_id" : ObjectId("511bf79298bb011e3a33747d"), "val" : 9 }
{ "_id" : ObjectId("511bf79698bb011e3a33747e"), "val" : 4 }
{ "_id" : ObjectId("511bf79d98bb011e3a33747f"), "val" : 20 }
db.col.find().sort({val: 1}).limit(1); //min
{ "_id" : ObjectId("511bf79698bb011e3a33747e"), "val" : 4 }
db.col.find().sort({val: -1}).limit(1); //max
{ "_id" : ObjectId("511bf79d98bb011e3a33747f"), "val" : 20 }
Upvotes: 2