Select multiple values with MongoDB OR operator

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents −

> db.demo270.insertOne({"ClientName":"Chirs","Age":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e481e371627c0c63e7dbab8")
}
> db.demo270.insertOne({"ClientName":"David","Age":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e481e3d1627c0c63e7dbab9")
}
> db.demo270.insertOne({"ClientName":"Bob","Age":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e481e431627c0c63e7dbaba")
}
> db.demo270.insertOne({"ClientName":"Carol","Age":36});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e481e491627c0c63e7dbabb")
}

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

> db.demo270.find();

This will produce the following output −

{ "_id" : ObjectId("5e481e371627c0c63e7dbab8"), "ClientName" : "Chirs", "Age" : 34 }
{ "_id" : ObjectId("5e481e3d1627c0c63e7dbab9"), "ClientName" : "David", "Age" : 31 }
{ "_id" : ObjectId("5e481e431627c0c63e7dbaba"), "ClientName" : "Bob", "Age" : 31 }
{ "_id" : ObjectId("5e481e491627c0c63e7dbabb"), "ClientName" : "Carol", "Age" : 36 }

Following is the query to select multiple values with OR operator −

> db.demo270.find({
...   "$or" : [
...      {
...         "ClientName" : "Carol"
...      },
...      {
...         "Age" : 31
...      }
...   ]
...}
...);

This will produce the following output −

{ "_id" : ObjectId("5e481e3d1627c0c63e7dbab9"), "ClientName" : "David", "Age" : 31 }
{ "_id" : ObjectId("5e481e431627c0c63e7dbaba"), "ClientName" : "Bob", "Age" : 31 }
{ "_id" : ObjectId("5e481e491627c0c63e7dbabb"), "ClientName" : "Carol", "Age" : 36 }
raja
Published on 31-Mar-2020 08:48:09
Advertisements