MongooseJS – 如何find最大值的元素?
我正在使用MongoDB,MongooseJS和Nodejs。
我有一个集合(称为成员)与以下字段 –
Country_id,Member_id,Name,Score
我想写一个查询返回成员的国家id = 10的最高分数
我在MongooseJS中找不到合适的文档。
我发现这在StackOverflow(这是MongoDB代码)
Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) { var max = doc.last_mod; });
但是我怎么把这个翻译成MongooseJS?
Member .findOne({ country_id: 10 }) .sort('-score') // give me the max .exec(function (err, member) { // your callback code });
检查mongoose的查询 ,他们是相当不错的。
如果您不想再次编写相同的代码,您也可以将静态方法添加到您的成员模型中,如下所示:
memberSchema.statics.findMax = function (callback) { this.findOne({ country_id: 10 }) // 'this' now refers to the Member class .sort('-score') .exec(callback); }
稍后通过Member.findMax(callback)
你不需要Mongoose文档来做到这一点。 Plain MongoDb将完成这项工作。
假设你有你的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 }
以下查询将返回一个光标到文档,您正在寻找:
db.Member.find({country_id : 10}).sort({score : -1}).limit(1)
find()
比findOne()
更快 。
用find().limit(1)
返回一个文档的数组。 要获取文档对象,您必须获取第一个数组元素maxResult[0]
。
让萨尔瓦多的答案更完整
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] });