MongoDB OR operator ( $or )

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.

  • You can use this operator in methods like find(), update(), etc. according to your requirments.
  • You can also use this operator with text queries, GeoSpatial queries, and sort operations.
  • When MongoDB evaluating the clauses in the $or expression, it performs a collection scan. Or if all the clauses in $or expression are supported by indexes, then MongoDB performs index scans.
  • You can also nest $or operation.

Syntax:

{ $or: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.



Matching values using $or operator:

In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$or: [{branch: "ECE"},
                     {joiningYear: 2017}]}).pretty()

chevron_right


Matching values in nested/embedded documents using $or operator:

In this example, we are retrieving only those employee’s documents whose age is 24 or state is Delhi.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$or: [{"personal.age": 24}, 
                     {"personal.state": "Delhi"}]}).pretty()

chevron_right


Matching values in an array using $or operator:

In this example, we are retrieving only those employee’s documents that at least match one of value in the given array.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$or: [{language: {$in: ["Java", "C"]}}]}).pretty()

chevron_right



Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.