Search code examples
rmongodbrmongodb

How to construct rmongodb query using $and operator


I want to use rmongodb to access MongoDB database in R. I tried to construct following query:

{'$and': [{_id: {'$gte': '2013-01-01'}}, {_id: {'$lte': '2013-01-10'}}]}

I tried three different methods to create bson object, having no luck for all.

Method 1:

buf = mongo.bson.buffer.create()
mongo.bson.buffer.start.array(buf, '$and')
mongo.bson.buffer.append(buf, '_id', list('$gte'='2013-01-01'))
mongo.bson.buffer.append(buf, '_id', list('$lte'='2013-01-10'))
mongo.bson.buffer.finish.object(buf)
bson = mongo.bson.from.buffer(buf)

Method 2:

    buf = mongo.bson.buffer.create()
mongo.bson.buffer.start.array(buf, '$and')
mongo.bson.buffer.start.object(buf, '_id')
mongo.bson.buffer.append(buf, '$gte', '2013-01-01')
mongo.bson.buffer.finish.object(buf)
mongo.bson.buffer.start.object(buf, '_id')
mongo.bson.buffer.append(buf, '$lte', '2013-01-10')
mongo.bson.buffer.finish.object(buf)
mongo.bson.buffer.finish.object(buf)
bson = mongo.bson.from.buffer(buf)

Method 3:

mongo.bson.from.list(list('$and'=list('_id' = list('$lte'='2013-01-10'), '_id' = list('$gte'='2013-01-01'))))

None of them works. All return empty result.

I searched for sometime, the only similar question asked is rmongodb: using $or in query The solution was to use RMongo instead, which is not available for R 2.50.

I am stuck in this problem for several days. if I cannot find a solution, I would have to write an external script with python and call it from R.


Solution

  • I don't know R, but you don't actually need to use $and for that query. This is a bit simpler and should be easier to translate to R:

    {_id: {'$gte': '2013-01-01', '$lte': '2013-01-10'}}