Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find values with OR operator in MongoDB and format the result.?
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
}Advertisements