OR operations in query expressions

Query objects in Mongo by default AND expressions together.

$in

The $in operator indicates a "where value in ..." expression.  For expressions of the form x == a OR x == b, this can be represented as

{ x : { $in : [ a, b ] } }

$or

v1.5.3+

The $or operator lets you use a boolean or expression to do queries. You give $or a list of expressions, any of which can satisfy the query.

Simple:

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

With another field

db.foo.find( { name : "bob" , $or : [ { a : 1 } , { b : 2 } ] } )

The $or operator retrieves matches for each or clause individually and eliminates duplicates when returning results.

$where

We can provide arbitrary Javascript expressiosn to the server via the $where operator.  This provides a means to perform OR operations.  For example in the mongo shell one might invoke:

db.mycollection.find( { $where : function() { return this.a == 3 || this.b == 4; } } );

The following syntax is briefer and also works; however, if additional structured query components are present, you will need the $where form:

db.mycollection.find( function() { return this.a == 3 || this.b == 4; } );

See Also


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus