MongoDB - And & OR Operation - MongoDB Tutorial



MongoDB - And & OR Operation

  • Considering the mongodb-AND & OR Operation, the find() method will display the data which satisfy both the AND & OR condition in order to display the certain data’s.
  • In mongodb if we need to perform the or operation means we need to use $or keyword. Similarly in the find() method if we pass multiple keys by separating them by ',' (commas) then MongoDB treats it as AND condition.

Syntax for AND Operation :

db.collection.find({key1:value1, key2:value2}).pretty()

Syntax for OR Operation :

db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Sample Query :

db.wikitechy4.find(
	{
	"details":"last row inserted", 
	$or:
	  [
	     {"author":"jln"},
 	     {"articlecount":"50"}
           ]
          }
).pretty()

MongoDb


Output

MongoDb
  1. Here in this statement, we display the data from the collection “wikitechy4”, where only the author name “jln” will display that data’s.
  2. Here in this statement, we display the data from the collection “wikitechy4” where only the author name “jln” will display the data’s.
  3. In this statement we display the data from the collection “wikitechy4” where only the author name “jln” & the article count as “50” constrain will be displayed using find() rich query.
  4. Here in this output statement, we use the AND & OR operation query in which both the condition must be satisfy both the possibilities where, the output is initially performing OR operation after that it checks for the AND operation in the certain data.
  5. Here is the sample output data for executing the AND & OR Operation for the certain condition of query as shown above.


Related Searches to MongoDB - And & OR Operation - MongoDB Tutorial