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
.