MongoDB query with an 'or' condition?


To understand the query with an or condition, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.orConditionDemo.insertOne({"CustomerName":"Larry","ShippingDate":new ISODate("2018-01-29")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ec5262f684a30fbdfd56a")
}
> db.orConditionDemo.insertOne({"CustomerName":"Mike","ShippingDate":new ISODate("2019-04-13")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ec5362f684a30fbdfd56b")
}
> db.orConditionDemo.insertOne({"CustomerName":"Bob","ShippingDate":new ISODate("2019-02-21")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ec5422f684a30fbdfd56c")
}
> db.orConditionDemo.insertOne({"CustomerName":"David","ShippingDate":new ISODate("2019-03-15")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ec5532f684a30fbdfd56d")
}
> db.orConditionDemo.insertOne({"CustomerName":"John","ShippingDate":new ISODate("2019-03-19")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ec56c2f684a30fbdfd56e")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.orConditionDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8ec5262f684a30fbdfd56a"),
   "CustomerName" : "Larry",
   "ShippingDate" : ISODate("2018-01-29T00:00:00Z")
}
{
   "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"),
   "CustomerName" : "Mike",
   "ShippingDate" : ISODate("2019-04-13T00:00:00Z")
}
{
   "_id" : ObjectId("5c8ec5422f684a30fbdfd56c"),
   "CustomerName" : "Bob",
   "ShippingDate" : ISODate("2019-02-21T00:00:00Z")
}
{
   "_id" : ObjectId("5c8ec5532f684a30fbdfd56d"),
   "CustomerName" : "David",
   "ShippingDate" : ISODate("2019-03-15T00:00:00Z")
}
{
   "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"),
   "CustomerName" : "John",
   "ShippingDate" : ISODate("2019-03-19T00:00:00Z")
}

Here is the query with multiple or conditions −

> db.orConditionDemo.find({$or: [{ShippingDate: {$gte: new ISODate()}}, {ShippingDate: null}]}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"),
   "CustomerName" : "Mike",
   "ShippingDate" : ISODate("2019-04-13T00:00:00Z")
}
{
   "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"),
   "CustomerName" : "John",
   "ShippingDate" : ISODate("2019-03-19T00:00:00Z")
}

Updated on: 30-Jul-2019

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements