Examples of Find() Method
To understand Find Method in MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called student of gfg database which contains informations
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Example 1
Let’s Find all student records from the “student” collection where the student’s age is exactly 18.
db.student.find()
Output:
Explanation: In the above query, we have find all the documents in the students collections in MongoDB.
Example 2
Find all the documents present in the collection:
db.student.find({age:18})
Output:
Explanation: In the above query, we have find those students whose age is 18.
Example 3
Let’s Find student records from the “student” collection where the student’s math score is 230 and science score is 234.
db.student.find({score:{math: 230, science: 234}})
Output:
Explanation:
In the above MongoDB query, we have searches for student records in the “student” collection based on their exam performance in two subjects. It retrieves documents where the student’s math score is exactly 230 and their science score is exactly 234. The query uses a nested document to specify these conditions within the “score” field of each student record.
MongoDB – Find() Method
MongoDB provides powerful methods for retrieving documents from its collections with find()
and findOne()
methods. The find()
method supports complex queries with various operators and allows specifying which fields to include or exclude and optimizing performance by using indexes.
In this article, We will learn about the Find() Method by understanding various examples of Find with various operators and so on.