在nodeJS和MongoDb中找到一个最大值

Find a maximum value in a collection in nodeJS and MongoDb

本文关键字:一个 最大值 nodeJS MongoDb      更新时间:2023-09-26

我有一个非常简单的查询,但只是不能得到它的工作。我有一个名为users的集合,它有uid字段。我想从中得到uid字段的最大值。以下是我所做的:-

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

但是这给了我99,而我的值高达300。我猜它是将每个元素与9匹配,然后进行比较。正确答案应该是314

集合中条目的保存方式如下:-

{ 
 {
 _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)

将查找所有用户,然后对它们进行排序,然后只返回第一个。