Search code examples
scalamongodbcasbah

Querying by Comparing to ObjectId


I have val maxId = new ObjectId(...) and I want to query something like this: collection.find("_id" $lte maxId). This is a compilation failure since ObjectId doesn't include the appropriate trait ValidDateOrNumericType. How to properly query objects by comparing their ID?

In the Mongo shell this seems to be possible:

> db.test.find({"_id": {$lte: ObjectId("4e825d2f84ae30e970bc0f95")}})
{ "_id" : ObjectId("4e82540684ae236af6e72177")}
{ "_id" : ObjectId("4e825baa84aea840b82e0278")}
...
>

Also with the Java driver it works:

query.put("_id", new BasicDBObject("$lte", new ObjectId("4e825d2f84ae30e970bc0f95")))

Is this doable with Casbah?


Solution

  • With Casbah this can not be done, since ObjectId does not convert to ValidDateOrNumericType. I ended up using the Java API:

    collection.find(new QueryBuilder().put("_id").lessThanEquals(maxId).get())