tags:

views:

54

answers:

2

What's the best way to do a query like this in MongoDB?

SELECT * FROM things WHERE (a = 1 or b = 1) and (c = 2 or d = 2)

Thanks.

+1  A: 

You can use the $or expression.

db.things.find( { $or : [ { a : 1}, { b : 1 } ], $or : [ { c : 2 }, { d : 2 } ] } )

halfdan
Right idea but clearly the wrong answer. Test case: db.things.save({"b" : 1, "c" : 2}); db.things.find( { $or : [ { a : 1, b : 1 } , { c : 2, d : 2 } ] } ); Satisfies both halves of the and clause from above, but does not come back with your query.
Gates VP
@Gates VP: You're right indeed. Thanks for noticing, I've updated my answer.
halfdan
+1  A: 

@Drew, the correct answer for this query is the following:

db.test.find( { $or : [ { a : 1}, { b : 1 } ], $or : [ { c : 2 }, { d : 2 } ] } )

That's a = 1 or b = 1 and c = 2 or d = 2. If you look at the code, you'll notice that you have two or clauses separated by a comma. When doing a find, the comma is effectively the and clause.

For docs on using the $or clause, see here.

Gates VP
Thanks, now I wonder how I use that with a the node-mongodb-native library. It is not a valid javascript object because it has two keys of the same name.
Drew LeSueur
Also, is there any documentation on this?
Drew LeSueur
OK, NodeJS and NodeMongo are really new. We're talking about a first commit on July 4th. Honestly I would just go to the github page and message the developers directly: http://github.com/christkv/node-mongodb-native
Gates VP