How to construct rmongodb query using $and operator

血红的双手。 提交于 2019-12-12 02:05:54

问题


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.


回答1:


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'}}



回答2:


your way of creating an mongo bson array is wrong. You are missing the parts

mongo.bson.buffer.start.object(buf, "0")
...
mongo.bson.buffer.finish.object(buf)
mongo.bson.buffer.start.object(buf, "1")
...
mongo.bson.buffer.finish.object(buf)

For a working example please check the latest comment on: https://github.com/mongosoup/rmongodb/issues/17

I hope this works for now. I am working on an easier solution!



来源:https://stackoverflow.com/questions/14272458/how-to-construct-rmongodb-query-using-and-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!