Evaluate one or more expressions using the $or operator in MongoDB. Following is the syntax −
db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty();
Let us first create a collection with documents −
> db.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b80a6d78f205348bc61b") } > db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8266d78f205348bc61c") } > db.orOperatorDemo.insertOne({"StudentNames":["John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8346d78f205348bc61d") }
Following is the query to display all documents from a collection with the help of find() method −
> db.orOperatorDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8266d78f205348bc61c"), "StudentNames" : [ "Robert", "Chris", "David" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }
Here is the query to $or operator syntax −
> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }