【问题标题】:Finding the maxing value of an attribute in mongoDB using casbah使用 casbah 在 mongoDB 中查找属性的最大值
【发布时间】:2025-11-24 08:05:02
【问题描述】:

我是 casbah 和 mongodb 的新手。我正在尝试编写一个 scala 代码来查找列的最大值。

例如:

  {"_id"=1,value = "a"}
  {"_id"=2,value = "b"}
  {"_id"=3,value = "c"}
  {"_id"=4,value = "d"}

程序应显示 id 的最大数量为 4 你能告诉我怎么做吗?

谢谢!!

【问题讨论】:

    标签: mongodb scala casbah


    【解决方案1】:

    这是非常基本的东西,所以我真的建议您查看MongoDB tutorials 以获得基本的基础。或者,还有来自 MongoDB 的免费 online education platform

    关于手头的问题 - 你如何找到最大的_id?求最大值的方法是简单地把数据按降序排列,取第一项。由于_id 会自动编入索引,因此这将是一个便宜的操作。有一个 findOne method 接受查询、要返回的字段和排序文档,使用它我们可以获得具有最高 _id 的文档:

      // Add some test data:
      collection += MongoDBObject("_id" -> 1, "value" -> "a")
      collection += MongoDBObject("_id" -> 2, "value" -> "b")
      collection += MongoDBObject("_id" -> 3, "value" -> "c")
      collection += MongoDBObject("_id" -> 4, "value" -> "d")
    
      // findOne
      val query = MongoDBObject() // All documents
      val fields = MongoDBObject("_id" -> 1) // Only return `_id`
      val orderBy = MongoDBObject("_id" -> -1) // Order by _id descending
    
      // Run the query
      collection.findOne(query, fields, orderBy)
    

    在 findOne 中,我们只返回 _id 字段,这意味着我们可以利用索引仅查找此数据,因为我们不需要文档中的任何其他数据。

    FindOne 返回一个Option[MongoDocument],包含文档将包含最高的_id

    【讨论】:

    • 首先感谢您的回复。我尝试了您提到的类似代码。但是我收到一个错误-“资源路径位置类型类型不匹配;找到:com.mongodb.casbah.commons.Imports.DBObject(扩展为)com.mongodb.DBObject required:com.mongodb.casbah.Imports.ReadPreference(其中扩展为)com.mongodb.ReadPreference”。我认为 findOne 不接受超过 2 个值。你能帮帮我吗?