简体   繁体   English

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

[英]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. 我有一个名为users的集合,该集合具有uid字段。 I want to get the maximum value of uid field from it. 我想从中获取uid字段的最大值。 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. 但这给了我99,而我的值最多为300。我猜它是将每个元素都匹配为9,然后进行比较。 The correct answer should be 314 正确答案应该是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. 会找到所有用户,然后对其进行排序,然后只返回第一个用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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