node.js MongooseJS - 如何找到具有最大值的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19751420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongooseJS - How to find the element with the maximum value?
提问by geeky_monster
I am using MongoDB , MongooseJS and Nodejs.
我正在使用 MongoDB、MongooseJS 和 Nodejs。
I have a Collection ( called Member ) with the following Fields -
我有一个包含以下字段的集合(称为 Member ) -
Country_id , Member_id , Name, Score
Country_id、Member_id、姓名、分数
I want to write a query which returns the Member with the max Score where Country id = 10
我想编写一个查询,该查询返回具有最大分数的成员,其中 Country id = 10
I couldnt find suitable documentation for this in MongooseJS.
我在 MongooseJS 中找不到合适的文档。
I found this at StackOVerflow ( this is MongoDB code )
我在 StackOverflow 上找到了这个(这是 MongoDB 代码)
Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) {
var max = doc.last_mod;
});
But how do I translate the same to MongooseJS ?
但是我如何将其翻译成 MongooseJS 呢?
回答by tmaximini
Member
.findOne({ country_id: 10 })
.sort('-score') // give me the max
.exec(function (err, member) {
// your callback code
});
Check the mongoose docs for querying, they are pretty good.
检查mongoose docs for querying,它们非常好。
If you dont't want to write the same code again you could also add a static method to your Member model like this:
如果您不想再次编写相同的代码,您还可以向您的 Member 模型添加一个静态方法,如下所示:
memberSchema.statics.findMax = function (callback) {
this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
.sort('-score')
.exec(callback);
}
And call it later via Member.findMax(callback)
稍后通过调用它 Member.findMax(callback)
回答by Salvador Dali
You do not need Mongoose documentation to do this. Plain MongoDb will do the job.
您不需要 Mongoose 文档来执行此操作。普通的 MongoDb 将完成这项工作。
Assume you have your Membercollection:
假设你有你的Member收藏:
{ "_id" : ObjectId("527619d6e964aa5d2bdca6e2"), "country_id" : 10, "name" : "tes2t", "score" : 15 }
{ "_id" : ObjectId("527619cfe964aa5d2bdca6e1"), "country_id" : 10, "name" : "test", "score" : 5 }
{ "_id" : ObjectId("527619e1e964aa5d2bdca6e3"), "country_id" : 10, "name" : "tes5t", "score" : -6 }
{ "_id" : ObjectId("527619e1e964aa5d2bdcd6f3"), "country_id" : 8, "name" : "tes5t", "score" : 24 }
The following query will return you a cursor to the document, you are looking for:
以下查询将返回您正在查找的文档的光标:
db.Member.find({country_id : 10}).sort({score : -1}).limit(1)
回答by Melissa
It might be fasterto use find()than findOne().
这可能是更快的使用find()比findOne()。
With find().limit(1)an array of the one document is returned. To get the document object, you have to do get the first array element, maxResult[0].
用find().limit(1)一个数组返回一个文档。要获取文档对象,您必须获取第一个数组元素maxResult[0].
Making Salvador's answer more complete ...
使萨尔瓦多的答案更加完整......
var findQuery = db.Member.find({country_id : 10}).sort({score : -1}).limit(1);
findQuery.exec(function(err, maxResult){
if (err) {return err;}
// do stuff with maxResult[0]
});
回答by Wesley Williams
This is quick and easy using the Mongoose Query Helpers.
使用 Mongoose 查询助手可以快速轻松地完成此操作。
The general form for this could be:
其一般形式可能是:
<Your_Model>.find()
.sort("-field_to_sort_by")
.limit(1)
.exec( (error,data) => someFunc(error,data) {...} );
tldr: This will give you an array of a single item with the highest value in 'field_to_sort_by'. Don't forget to access it as data[0], like I did for an hour.
tldr:这将为您提供一个数组,其中包含“field_to_sort_by”中具有最高值的单个项目。不要忘记将它作为 data[0] 访问,就像我做了一个小时一样。
Long-winded: Step-by-step on what that string of functions is doing...
长篇大论:一步一步地了解这串函数正在做什么......
Your_Model.find()starts the query, no args needed.
Your_Model.find()开始查询,不需要参数。
.sort("-field_to_sort_by")sorts the everything in descending order. That minus-sign in front of the field name specifies to sort in descending order, you can discard it to sort in ascending order and thus get the document with the minimum value.
.sort("-field_to_sort_by")按降序对所有内容进行排序。字段名前面的那个减号表示按降序排序,你可以舍弃它按升序排序,从而得到最小值的文档。
.limit(1)tells the database to only return the first document, because we only want the top-ranked document.
.limit(1)告诉数据库只返回第一个文档,因为我们只想要排名靠前的文档。
.exec( (error,data) => someFunc(error,data) {...} )finally passes any error and an array containing your document to into your function. You'll find your document in data[0]
.exec( (error,data) => someFunc(error,data) {...} )最后将任何错误和包含您的文档的数组传递到您的函数中。您会在其中找到您的文档data[0]
回答by Sinandro
You can also use the $maxoperator:
您还可以使用$max运算符:
// find the max age of all users
Users.aggregate(
{ $group: { _id: null, maxAge: { $max: '$age' }}}
, { $project: { _id: 0, maxAge: 1 }}
, function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { maxAge: 98 } ]
});

