Fetch multiple documents in MongoDB query with OR condition?


Let us create a collection with documents −

> db.demo362.insertOne({"ClientName":"John","ClientProject":"School Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a77454a481fef8ec7a1c")
}
> db.demo362.insertOne({"ClientName":"David","ClientProject":"Library Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a78454a481fef8ec7a1d")
}
> db.demo362.insertOne({"ClientName":"Mike","ClientProject":"Event Tracker"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a7a054a481fef8ec7a1e")
}
> db.demo362.insertOne({"ClientName":"Carol","ClientProject":"Hospital Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a7b754a481fef8ec7a1f")
}

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

> db.demo362.find();

This will produce the following output −

{ "_id" : ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName" : "John", "ClientProject" : "School Management System" }
{ "_id" : ObjectId("5e56a78454a481fef8ec7a1d"), "ClientName" : "David", "ClientProject" : "Library Management System" }
{ "_id" : ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName" : "Mike", "ClientProject" : "Event Tracker" }
{ "_id" : ObjectId("5e56a7b754a481fef8ec7a1f"), "ClientName" : "Carol", "ClientProject" : "Hospital Management System" }

Following is the query to fetch multiple documents −

> db.demo362.find({$or: [{"ClientName":"John"}, {"ClientProject": "Event Tracker" }]});

This will produce the following output −

{ "_id" : ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName" : "John", "ClientProject" : "School Management System" }
{ "_id" : ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName" : "Mike", "ClientProject" : "Event Tracker" }

Updated on: 02-Apr-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements