Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find values with OR operator in MongoDB and format the result.?
Use $or operator to fetch values matching any of multiple conditions and pretty() to format the result with proper indentation and readability.
Syntax
db.collection.find({
$or: [
{ field1: value1 },
{ field2: value2 }
]
}).pretty();
Sample Data
Let us create a collection with documents:
db.demo304.insertMany([
{ "StudentName": "Chris", "StudentAge": 23 },
{ "StudentName": "David", "StudentAge": 22 },
{ "StudentName": "Mike", "StudentAge": 24 },
{ "StudentName": "Carol", "StudentAge": 22 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4ea3ccf8647eb59e562034"),
ObjectId("5e4ea3d7f8647eb59e562035"),
ObjectId("5e4ea3e2f8647eb59e562036"),
ObjectId("5e4ea3eef8647eb59e562037")
]
}
Display all documents from the collection:
db.demo304.find();
{ "_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 }
Example: Using $or Operator with pretty()
Find students with name "David" OR age 22 and format the output:
db.demo304.find({
$or: [
{ "StudentName": "David" },
{ "StudentAge": 22 }
]
}).pretty();
{
"_id": ObjectId("5e4ea3d7f8647eb59e562035"),
"StudentName": "David",
"StudentAge": 22
}
{
"_id": ObjectId("5e4ea3eef8647eb59e562037"),
"StudentName": "Carol",
"StudentAge": 22
}
Key Points
-
$orreturns documents that match any of the specified conditions -
pretty()formats output with proper JSON indentation for better readability - Both David and Carol are returned - David matches by name, Carol matches by age
Conclusion
The $or operator enables flexible querying by matching multiple conditions, while pretty() improves output readability. This combination is essential for complex searches with formatted results.
Advertisements
