Evaluate one of more values from a MongoDB collection with documents

MongoDBDatabaseBig Data Analytics

To evaluate one or more values, use $or along with find(). Let us create a collection with documents −

> db.demo174.insertOne({"StudentName":"Chris","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c709e4f06af551997e5")
}
> db.demo174.insertOne({"StudentName":"David","CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c779e4f06af551997e6")
}
> db.demo174.insertOne({"StudentName":"Bob","CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c7e9e4f06af551997e7")
}

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

> db.demo174.find();

This will produce the following output −

{ "_id" : ObjectId("5e383c709e4f06af551997e5"), "StudentName" : "Chris", "CountryName" : "US" }
{ "_id" : ObjectId("5e383c779e4f06af551997e6"), "StudentName" : "David", "CountryName" : "UK" }
{ "_id" : ObjectId("5e383c7e9e4f06af551997e7"), "StudentName" : "Bob", "CountryName" : "AUS" }

Following is the query to evaluate one or more values. Here, we are fetching more than one value i.e. student “David” or country “US” −

> db.demo174.find({$or:[{"StudentName":"David"},{"CountryName":"US"}]});

This will produce the following output −

{ "_id" : ObjectId("5e383c709e4f06af551997e5"), "StudentName" : "Chris", "CountryName" : "US" }
{ "_id" : ObjectId("5e383c779e4f06af551997e6"), "StudentName" : "David", "CountryName" : "UK" }
raja
Published on 27-Mar-2020 06:50:20
Advertisements