【问题标题】:MongooseJS - How to find the element with the maximum value?MongooseJS - 如何找到具有最大值的元素?
【发布时间】:2013-11-14 02:37:30
【问题描述】:

我正在使用 MongoDB、MongooseJS 和 Nodejs。

我有一个包含以下字段的集合(称为成员) -

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;
});

但是如何将它翻译成 MongooseJS 呢?

【问题讨论】:

    标签: node.js mongodb mongoose max database


    【解决方案1】:
    Member
      .findOne({ country_id: 10 })
      .sort('-score')  // give me the max
      .exec(function (err, member) {
    
        // your callback code
    
      });
    

    查看the mongoose docs for querying,他们很不错。

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

    memberSchema.statics.findMax = function (callback) {
    
      this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
        .sort('-score')
        .exec(callback);
    }
    

    稍后通过Member.findMax(callback)调用它

    【讨论】:

      【解决方案2】:

      您不需要 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 }
      

      以下查询会将光标返回到您正在查找的文档:

       db.Member.find({country_id : 10}).sort({score : -1}).limit(1)
      

      【讨论】:

      • 谢谢!我一直在我的代码中使用 Mongoose,如果我继续这样做会很好。
      • Salvador Dali - 当然,我可以在 Mongoose 代码之间插入它并使其工作。但我想知道这样做的猫鼬风格。谢谢!!
      【解决方案3】:

      使用find() 可能是faster 而不是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]
      
      });
      

      【讨论】:

        【解决方案4】:

        使用 Mongoose 查询助手可以快速轻松地完成此操作。

        一般形式可以是:

        <Your_Model>.find()
           .sort("-field_to_sort_by")
           .limit(1)
           .exec( (error,data) => someFunc(error,data) {...} );
        

        tldr: 这将为您提供在“field_to_sort_by”中具有最高值的单个项目的数组。不要忘记以 data[0] 的形式访问它,就像我做了一个小时一样。

        冗长:逐步了解该字符串的功能...

        Your_Model.find() 开始查询,不需要任何参数。

        .sort("-field_to_sort_by") 按降序对所有内容进行排序。字段名前面的那个减号指定降序排序,你可以舍弃它升序排序,从而得到最小值的文档。

        .limit(1) 告诉数据库只返回第一个文档,因为我们只想要排名靠前的文档。

        .exec( (error,data) =&gt; someFunc(error,data) {...} ) 最终将任何错误和包含您的文档的数组传递给您的函数。您可以在data[0]中找到您的文档

        【讨论】:

          【解决方案5】:

          您也可以使用$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 } ]
          });
          

          【讨论】:

            猜你喜欢
            • 2016-05-29
            • 2011-02-22
            • 2015-08-17
            • 1970-01-01
            • 2017-01-17
            • 2020-07-23
            • 1970-01-01
            • 2013-01-03
            • 2019-02-24
            相关资源
            最近更新 更多