MongoDB

MongoDB Find Functions Examples

MongoDB has various methods which are used for querying the documents of the collection. Among these functions of MongoDB, we have the find() function. The find() method in MongoDB is used to retrieve the documents from a collection and returns a cursor to the targeted documents. The term “cursor” here refers to a pointer that is linked to a document when we use the find() method. Moreover, two parameters, “selection criteria” and the “projection”, help compensate for the find() method, which we can use to retrieve a particular record. We will discuss further details with the example implementations.

How Is the Find() Function Used in MongoDB?

As we already discussed, the MongoDB find() function returns the specific documents from the collection. So, we create the MongoDB database by specifying the following command of MongoDB:

test> use UniversityStudents

switched to db UniversityStudents

The “UniveristyStudent” is the name of our MongoDB collection in which we utilize to perform the find() function tasks. Now, the collection is created in our MongoDB. We insert the documents by invoking the MongoDB insertMany() method. The document contains different fields whose values are changed. The sample insertion of numerous documents into MongoDB is shown in the following:

UniversityStudents>db.UniversityStudents.insertMany([
      {
          "Registration_Number": 009,
          "Student_Name": "Richard",
          "Batch_Number": 2021,
          "Degree": "IT",
          "Courses" : ["C#", "Java", "PHP"]
      },
      {
          "Registration_Number": 023 ,
          "Student_Name": "Daniel",
          "Batch_Number": 2019,
          "Degree": "SE",
          "Courses" : ["DSA", "Web Development", "Perl"]
      },
      {
          "Registration_Number": 002,
          "Student_Name": "Charles",
          "Batch_Number": 2021,
          "Degree": "CS",
          "Courses" : ["C++", "Java", "Ruby"]
      },
      {          
         "Registration_Number": 017,
          "Student_Name": "Jessica",
          "Batch_Number": 2020,
          "Degree": "CS",
          "Courses" : ["C++", "Computing", "Ruby"]
              },

      {
          "Registration_Number": 005 ,
          "Student_Name": "Kyle",
          "Batch_Number": 2008,
          "Degree": "IT",
          "Courses" : ["C#", "Java", "PHP"]
          }
  ])

The query command upon execution acknowledges the true results which means that all the documents of our collection are inserted with the MongoDB requirements. There are four inserted IDs in our “UniversityStudent” collection.

Example 1: Using the Find() Function in MongoDB

Sometimes, we want to acquire all the documents from the database. Then, the find() function query is needed to filter out the documents one by one. The find() function with an empty argument value only returns all the documents from the provided collection. Here, we have a query using the find() function which is assigned with no parametric values.

command 1:

db.UniversityStudents.find()

The find() function gives all the document one by one in a way that we insert at the time of creating the collection. The following MongoDB shell screenshot displays the required output of the find() function:

Example 2: Using the Find() Function Empty() Argument in MongoDB

The find() function of MongoDB also takes the argument value to find any document from the collection. But, we provide the find() function with the empty() argument. The find() function gets all the documents of the collection like in the previous example but takes the empty parameter which denotes the documents. The query of find() function with empty({}) document as argument is provided like the following:

command 2:

db.UniversityStudents.find({})

The query of the given find() function retrieves all the following “UniversityStudents” collection documents in a given sequence one by one because of the empty “{}” parameter.

Example 3: Using the Find() Function to Find a Specific Document in MongoDB

The find() function is also used for the purpose of querying a single field based on the referring document. Just noticed that we provide the following command where the find() method is specified with the argument. The argument is the single field “Resgistration_Number” from the documents whose values are also given. The find() function only finds the associated value of the field for the document if it exists in the collection.

command 3:

db.UniversityStudents.find({Registration_Number:023})

The find() function query of MongoDB searches for the particular document appears on the following MongoDB shell while executing the command:

Example 4: Using the Find() Function Projection Parameter in MongoDB

The prior query of the find() function is embedded with the selection criteria parameter. The find() function can also be passed with another parameter which is denoted as the projection parameter along with the selection criteria parameter. The projection parameter contains a list of the fields that is included in the obtained document. As the query is given in the following which is called the find() method first, we give the empty selection criteria to retrieve all the documents. Next, the projection parameter is provided which is the “Student_Name” and the “ _id” field which is always included since it accepts this field from the MongoDB collection as a projection parameter. The projection parameter should be the Boolean values of “0” as false and “1” as true.

command 4:

db.UniversityStudents.find({},{Student_Name:1, _id:0})

The use of the projection parameter in the find() function only displays the “Student_Name” field values from the collection.

Example 5: Using the Find() Function in MongoDB to Limit the Documents

As we have seen in the previous example, only employing the find() function retrieves all the documents from the collection. We can also set a maximum for the number of documents from our collection that we intend to visualize. The limit() method of MongoDB is deployed after calling the find() method. The limit() method takes a single input of type number which is the maximum document that we want to retrieve. We have to execute the following query of the MongoDB which is called the limit() method along with the find() function.

command 5:

db.UniversityStudents.find().limit(3)

Notice the output that only three documents are fetched because the limit() method specifies the range of the document from the following collection:

Example 6: Using the Find() Function in MongoDB to Exclude the Given Field

All the document fields are sometimes unnecessary to retrieve from the MongoDB collection. If we want a field to be in a query but not be seen in the query’s results, we can exclude that specific field. We can easily accomplish this by specifying any field in the following query which uses projection. Here, we exclude the “Course” field and the “Batch_Number”.

command 6:

db.UniversityStudents.find({ "Degree": "CS" },{Courses: 0, Batch_Number:0 } );

The documents which are displayed in the MongoDB shell are excluded with the “Course” field and the “Batch_Number” because the Boolean value of “0” is assigned to them.

Example 7: Using the Find() Function in MongoDB with the Conditional Operator

All the previous find() function queries are straightforward. Now, we have a find() function query in MongoDB that imposes a condition on that particular document and only return the documents that successfully satisfy the criteria. We can use any of the conditional operators based on our requirements. Here, we use the “greater than” condition which inputs in the MongoDB as “$gt”. All the documents whose “Batch_Number” are greater than “2019” are filtered out by executing this query.

Command 7:

db.UniversityStudents.find({Batch_Number : {$gt : 2019}}

The three records from the MongoDB collection are retrieved in the output which successfully meets the conditional criteria.

Conclusion

The article’s objective is to explore the find() function of MongoDB. Here, we implemented the different queries for the find() function which retrieves the documents from the collection. The first example retrieved all the documents from the find() function. Next, we accomplished the specific documents from the find() function. Then, we implemented the query where the parameter projection is employed to retrieve the document that matches the selection query. Finally, we applied the conditional operation on the MongoDB find() function.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.