Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Multiple $or operations

Tags:

key

mongodb

How would I have multiple $or operations? So far I've tried the following but it silently ignores the 2nd $or.

{   $or: [{a: 2}, {a: 3}],    $or: [{b: 5}, {b: 4}] } 

I assume this is because I'm using two identical keys. Is there any way around this?

like image 294
Mike Neumegen Avatar asked Mar 01 '11 03:03

Mike Neumegen


People also ask

How do I write multiple conditions in MongoDB?

In MongoDB, we can apply the multiple conditions using the and operator. By applying the and operation we will select all the documents that satisfy all the condition expressions. We can use this operator in methods like find(), update() , etc as per the requirement.

How do I test multiple conditions in MongoDB?

Find Multiple Conditions Using the $or Operator The or operator in MongoDB is used to select or retrieve only documents that match at least one of the provided phrases. You can also use this operator in a method like a find() , update() , etc., as per the requirements.

How do I query multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

How $or works in MongoDB?

MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array.


1 Answers

Mongo 2.0 added an $and operator, so you can do a query like this:

db.things.find({$and: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] }) 

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and

like image 92
Nader Avatar answered Oct 04 '22 04:10

Nader