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 ValidDateOrNumericTyp开发者_StackOverflowe
. 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?
You can implement the comparison 'operator' as a method. To use it your ObjectId has to be on the left side of the comparison.
You can use the "pimp my library" to provide a implicit conversion to something that contains the comparison. (see this question How does ‘1 * BigInt(1)’ work and how can I do the same?)
Or you can implement a trait which offers the desired functionality.
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())
精彩评论