在nodeJS和MongoDb中查找集合中的最大值

时间:2014-03-10 11:15:04

标签: javascript node.js mongodb

我有一个非常简单的查询,但不能让它工作。 我有一个名为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
}
}

1 个答案:

答案 0 :(得分:1)

试试这个:

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

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