MongoDB to fetch documents with $or Operator

MongoDBDatabaseBig Data Analytics

The $or operator performs a logical OR operation on an array of two or more expressions. Let us create a collection with documents −

> db.demo674.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f33604263e90dac943eb")
}
> db.demo674.insertOne({Name:"David",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f33c04263e90dac943ec")
}
> db.demo674.insertOne({Name:"Bob",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f34204263e90dac943ed")
}
> db.demo674.insertOne({Name:"John",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f34804263e90dac943ee")
}

Display all documents from a collection with the help of find() method −

> db.demo674.find();

This will produce the following output −

{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 }
{ "_id" : ObjectId("5ea3f34804263e90dac943ee"), "Name" : "John", "Age" : 24 }

Following is the query to fetch documents with $or operator −

> db.demo674.find({$or:[{Name:"David"},{Age:21}]});

This will produce the following output −

{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 }
raja
Published on 13-May-2020 13:31:39
Advertisements