0

I am a newbie to casbah and mongodb. I am trying to write a scala code to find max value of of a column.

For example:

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

The program should display the max number of id as 4 Could you please let me know how to do this?

Thanks!!

optimus
  • 77
  • 1
  • 6

1 Answers1

1

This is quite basic stuff, so I really recommend looking through the MongoDB tutorials to get a basic grounding. Alternatively, there is a free online education platform from MongoDB!

Onto the matter at hand - how do you find the maximum _id? The way to find the maximum is to simply sort the data in descending order and take the first item. As _id is automatically indexed this will be a cheap operation. There is a findOne method that takes a query, the fields to return and a sort document and using that we can get the document with the highest _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)

In the findOne we only return the _id field meaning we can take advantage of the index only to look up this data as we don't need any other data from the document.

FindOne returns an Option[MongoDocument] and the containing document will contain the highest _id.

Ross
  • 17,861
  • 2
  • 55
  • 73
  • First of thanks for the response. I tried the similar code that you mentioned. But i get an error-"Resource Path Location Type type mismatch; found : com.mongodb.casbah.commons.Imports.DBObject (which expands to)com.mongodb.DBObject required: com.mongodb.casbah.Imports.ReadPreference(which expands to) com.mongodb.ReadPreference". I think findOne doesnt accept more than 2 values. Could you please help me ? – optimus Oct 14 '14 at 19:15