MongoDB $or operator

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

MongoDB provides $or operator to perform logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions>. It checks whether any of the specified condition match in the document or not.

Syntax of $or

{$or : expressions}

It returns the data that satisfy at least one of the expression.

Example

Suppose, we have the following 'students' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }

The given statement returns all those students either whose age is 11 or class is 5C.

db.students.find({"$or" : [{"age" : 11}, {"class" : "5C"}]});
Output of the above code: mongodb or operator

Similarly, the given statement returns all those students either whose age is 12 or class is "5A".

db.students.find({"$or" : [{"age" : 12}, {"class" : "5A"}]});
Output of the above code:
{ "_id" : ObjectId("60d1860b3379d41d51aa7133"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("60d1860b3379d41d51aa7137"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }





Read more articles


General Knowledge



Learn Popular Language