Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

r - rmongodb: using $or in query

I'm struggling to create a query using $or within R and rmongodb. What I'd like to emulate is this from cmdline mongo:

db.people.find( { $or : [ {"person.cell": { $exists : true } }, {"person.home": { $exists : true } } ] })

I'd like to pull records where either person.cell is not null, or person.home is not null. I can query each individually, but cannot get data back when I create the buffer in rmongodb with the $or, the R code using rmongodb looks like this:

l <- list("$exists"="true")
buf <- mongo.bson.buffer.create()
mongo.bson.buffer.start.array(buf, "$or")
mongo.bson.buffer.append.list(buf, "person.cell", l)
mongo.bson.buffer.append.list(buf, "person.home", l)
mongo.bson.buffer.finish.object(buf)  
b <- mongo.bson.from.buffer(buf)
mongo.find(mongo, "work.people", b)

That returns no records, no error, just an empty set. As I mentioned, I can do a find on either person.cell or person.home and get results, but not when I try to do an $or (in rmongodb) so that I pull records with either person.cell or person.home.

I've also tried this:

buf <- mongo.bson.buffer.create()
mongo.bson.buffer.start.array(buf, "$or")
mongo.bson.buffer.start.object(buf, "person.cell")
mongo.bson.buffer.append(buf, "$exists", "true")
mongo.bson.buffer.finish.object(buf)
mongo.bson.buffer.start.object(buf, "person.home")
mongo.bson.buffer.append(buf, "$exists", "true")
mongo.bson.buffer.finish.object(buf)
mongo.bson.buffer.finish.object(buf)
b <- mongo.bson.from.buffer(buf)
mongo.find(mongo, "work.people", b)

But I get the same empty set result (and "b" looks the same when I view it). I'm stuck on this one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

There is a bug in all the .to.list / .from.list / .append.list commands. I am working on an easier solution!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...