简体   繁体   中英

Find a maximum value in a collection in nodeJS and MongoDb

I have a very simple query but just cant get it working. I have a collection named users which has uid field. I want to get the maximum value of uid field from it. Following is what i do :-

   var options = { "sort": [['uid',-1]] };
    db.users.findOne({}, options , function(err, doc) {
    console.log("Returned #" + doc.uid + " documents");
}); 

But this gives me 99 while i have the values upto 300. I guess it is matching every element with 9 and then comparing it. The correct answer should be 314

Following is the way the entries are saved in collection :-

{ 
 {
 _id: "531181a3ec9af9107d2b4ccd",
 age: "0",
 carModel: "bullet motorcycle",
 chargePrice: "",
 contact: "",
 email: "",
 fbid: "1179803227",
 fromLat: "28.4594965",
 fromLon: "77.0266383",
 fromName: "Gurgaon, Haryana, India",
 fuelType: "Petrol",
 id: "215",
 image: "http://graph.facebook.com/1179803227/picture?type=large",
 name: "Sandeep Yadav",
 points: "0",
 regid: "abc",
 returnTime: "15:41 Hrs",
 sex: "0", 
 smoking: "No Smoking allowed",
 startTime: "15:41 Hrs",
 toLat: "28.510782",
 toLon: "77.048646",
 toName: "Sector 23 ,HUDA Market, Huda, Sector 23, Gurgaon, Haryana, India",
 uid: 311
},
{
 _id: "531181a3ec9af9107d2b4cce",
 age: "0",
 carModel: "2014 Nissan sentra",
 chargePrice: "USD 30",
 contact: "",
 email: "",
 fbid: "100001451156666",
 fromLat: "27.950575",
 fromLon: "-82.4571776",
 fromName: "Tampa, FL, United States",
 fuelType: "Petrol",
 id: "214",
 image: "http://graph.facebook.com/100001451156666/picture?type=large",
 name: "Kelly J. Dugan",
 points: "0",
 regid: "abc",
 returnTime: "23:04 Hrs",
 sex: "0",
 smoking: "Doesnt Matter",
 startTime: "16:02 Hrs",
 toLat: "25.7889689",
 toLon: "-80.2264393",
 toName: "Miami, FL, United States",
 uid: 308
}
}

try this:

db.users.find({}).sort("uid":-1).limit(1)

that will find all users, then sort them, and then just return the first one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM