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 MongoDB records based on a condition?
To find MongoDB records based on a condition, use the find() method with a query document that specifies the filtering criteria. The query document contains field-value pairs that define the conditions to match.
Syntax
db.collection.find({ field: value });
db.collection.find({ field: { $operator: value } });
Sample Data
Let us create a collection with student documents ?
db.students.insertMany([
{ "Name": "John", "Marks": 54 },
{ "Name": "Chris", "Marks": 35 },
{ "Name": "David", "Marks": 45 },
{ "Name": "Bob", "Marks": 40 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea702e4d346dcb074dc6f33"),
ObjectId("5ea702e6d346dcb074dc6f34"),
ObjectId("5ea702ebd346dcb074dc6f35"),
ObjectId("5ea702fad346dcb074dc6f36")
]
}
View All Documents
db.students.find();
{ "_id": ObjectId("5ea702e4d346dcb074dc6f33"), "Name": "John", "Marks": 54 }
{ "_id": ObjectId("5ea702e6d346dcb074dc6f34"), "Name": "Chris", "Marks": 35 }
{ "_id": ObjectId("5ea702ebd346dcb074dc6f35"), "Name": "David", "Marks": 45 }
{ "_id": ObjectId("5ea702fad346dcb074dc6f36"), "Name": "Bob", "Marks": 40 }
Example: Find Records with Condition
Find students with marks greater than 40 ?
db.students.find({ Marks: { $gt: 40 } });
{ "_id": ObjectId("5ea702e4d346dcb074dc6f33"), "Name": "John", "Marks": 54 }
{ "_id": ObjectId("5ea702ebd346dcb074dc6f35"), "Name": "David", "Marks": 45 }
Key Points
- Use comparison operators like
$gt,$lt,$gte,$ltefor numeric conditions - Multiple conditions can be combined using
$andor$oroperators - Empty query document
{}returns all documents
Conclusion
The find() method with query conditions allows precise document retrieval from MongoDB collections. Use comparison operators and logical operators to create complex filtering criteria for your data queries.
Advertisements
