Open In App

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. 

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. 




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

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. 




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

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. 




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


Article Tags :