grailsmongodbgroovygorm-mongodb

Find method not working in GMongo using $gt greater and less than operands


I'm using the GMongo library in Groovy to read items from MongoDB. The CacheItem class is a simple object to hold cache items, and each item has an expiration time which is set at the time when it's added to the mongo. When I read items from mongo, I only want to retrieve items that have not expired based on the expirationMillis field.

class CacheItem {
  def _id
  def cacheKey
  long expirationMillis
  def value
}

This works for retrieving items using the cacheKey

item = mongoDb.cache.findOne( cacheKey: "600")

But when I try to use criteria with greater than/less than convention against the expirationMillis, I can't seem to retrieve any documents..

long nowMillis = (new Date()).getTime()
item = mongoDb.cache.findOne( cacheKey: "600", expirationMillis: { $gt: nowMillis})

Am I using the wrong convention?


Solution

  • You have to escape $gt such that it looks like this:

    long nowMillis = (new Date()).getTime()
    item = mongoDb.cache.findOne( [ cacheKey: "600", expirationMillis: [ "\\\$gt" : nowMillis]]  as BasicDBObject)
    

    or

    long nowMillis = (new Date()).getTime()
    item = mongoDb.cache.findOne( [ cacheKey: "600", expirationMillis: [ '$gt' : nowMillis]]  as BasicDBObject )