MongooseJS - 如何找到具有最大值的元素?

gee*_*ter 17 database max mongoose mongodb node.js

我正在使用MongoDB,MongooseJS和Nodejs.

我有一个Collection(称为Member),包含以下字段 -

Country_id,Member_id,姓名,分数

我想编写一个查询,返回具有最大分数的成员,其中Country id = 10

我在MongooseJS找不到合适的文档.

我在StackOVerflow上发现了这个(这是MongoDB代码)

Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) {
     var max = doc.last_mod;
});
Run Code Online (Sandbox Code Playgroud)

但是我如何将其翻译成MongooseJS?

tma*_*ini 34

Member
  .findOne({ country_id: 10 })
  .sort('-score')  // give me the max
  .exec(function (err, member) {

    // your callback code

  });
Run Code Online (Sandbox Code Playgroud)

检查mongoose docs进行查询,它们非常好.

如果您不想再次编写相同的代码,您还可以向您的Member模型添加静态方法,如下所示:

memberSchema.statics.findMax = function (callback) {

  this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
    .sort('-score')
    .exec(callback);
}
Run Code Online (Sandbox Code Playgroud)

并稍后通过 Member.findMax(callback)


Sal*_*ali 12

您不需要Mongoose文档来执行此操作.普通的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 }
Run Code Online (Sandbox Code Playgroud)

以下查询将向您返回文档,您正在寻找:

 db.Member.find({country_id : 10}).sort({score : -1}).limit(1)
Run Code Online (Sandbox Code Playgroud)


Mel*_*ssa 5

这可能是更快的使用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]

});
Run Code Online (Sandbox Code Playgroud)