Find values with OR operator in MongoDB and format the result.?

MongoDBDatabaseBig Data Analytics

Use $or operator to fetch values and to format the result, use “pretty()”. Let us create a collection with documents −

> db.demo304.insertOne({"StudentName":"Chris","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3ccf8647eb59e562034")
}
> db.demo304.insertOne({"StudentName":"David","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3d7f8647eb59e562035")
}
> db.demo304.insertOne({"StudentName":"Mike","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3e2f8647eb59e562036")
}
> db.demo304.insertOne({"StudentName":"Carol","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3eef8647eb59e562037")
}

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

> db.demo304.find();

This will produce the following output −

{ "_id" : ObjectId("5e4ea3ccf8647eb59e562034"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e4ea3d7f8647eb59e562035"), "StudentName" : "David", "StudentAge" : 22 }
{ "_id" : ObjectId("5e4ea3e2f8647eb59e562036"), "StudentName" : "Mike", "StudentAge" : 24 }
{ "_id" : ObjectId("5e4ea3eef8647eb59e562037"), "StudentName" : "Carol", "StudentAge" : 22 }

Following is the query to get values with OR operator in MongoDB −

> db.demo304.find({ $or: [{ "StudentName": "David" }, { "StudentAge":22} ] } ).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e4ea3d7f8647eb59e562035"),
   "StudentName" : "David",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5e4ea3eef8647eb59e562037"),
   "StudentName" : "Carol",
   "StudentAge" : 22
}
raja
Published on 01-Apr-2020 07:30:38
Advertisements