Friday, 20 February 2015

mongoDB : $or operator


$or operator joins query clauses with a logical AND returns all documents that match the conditions of both clauses.

Syntax
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

$or operator takes array of expressions as input, each expression corresponds to a document.

> db.employee.find()
{ "_id" : 1, "firstName" : "Joel", "lastName" : "chelli", "salary" : 25000, "hobbies" : [ "watching movies", "playing games" ] }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies" ] }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "salary" : 65000, "hobbies" : [ "climbing hills", "dancing", "singing" ] }
{ "_id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy", "salary" : 50000, "hobbies" : [ "watching movies", "watching movies", "watching movies" ] }
{ "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Gurram", "salary" : 150000, "hobbies" : [ "hackning sites", "Reading books", "listening music" ] }
{ "_id" : 6, "firstName" : "BalaKrishna", "lastName" : "Gurram", "salary" : 80000, "hobbies" : [ "roaming around", "eating food" ] }
{ "_id" : ObjectId("54ba2de1f1c8f2149c000740"), "name" : "Krishna", "project" : "A350" }
{ "_id" : ObjectId("54ba2dfcf1c8f2149c000741"), "name" : "Krishna", "project" : 4 }


1.Get all documents where firstName is Gopi or type of the field “project” is double.

> db.employee.find({$or : [{"firstName" : {$eq: "Gopi"}}, {"project":{$type : 1}}]})
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "salary" : 65000, "hobbies" : [ "climbing hills", "dancing", "singing" ] }
{ "_id" : ObjectId("54ba2dfcf1c8f2149c000741"), "name" : "Krishna", "project" : 4 }


2.Get all the documents where firstBame is Joel or Anand or Ritwik. 
> db.employee.find({$or : [{"firstName" : {$eq: "Gopi"}}, {"firstName":{$eq : "Joel"}}, {"firstName" : {$eq : "Ritwik"}}]})
{ "_id" : 1, "firstName" : "Joel", "lastName" : "chelli", "salary" : 25000, "hobbies" : [ "watching movies", "playing games" ] }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "salary" : 65000, "hobbies" : [ "climbing hills", "dancing", "singing" ] }
{ "_id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy", "salary" : 50000, "hobbies" : [ "watching movies", "watching movies", "watching movies" ] }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment