MongoDB Query Document: db.collection.find() with Example

⚡ Smart Summary

MongoDB Query Document operations retrieve records from a collection using the db.collection.find() function. The method returns all documents by default, accepts filter criteria such as field matches and the $gt operator, and formats results with the forEach(printjson) command.

  • 🔍 find() Function: The db.collection.find() method retrieves documents from a MongoDB collection, returning every document when no filter is given.
  • 🎯 Filter Criteria: Passing a query object, such as {EmployeeName: “Smith”}, returns only the documents that match the condition.
  • Query Operators: Selection operators like $gt, $lt, and $in refine results, for example finding employees with an id greater than 2.
  • 🖨️ Readable Output: Chaining forEach(printjson) prints each returned document in a clean JSON format.
  • 🧾 Projection: A second argument to find() selects which fields to include or exclude from the results.

The method of fetching or getting data from a MongoDB database is carried out by using MongoDB queries. While performing a query operation, one can also use criteria’s or conditions which can be used to retrieve specific data from the database.

MongoDB provides a function called db.collection.find() which is used for retrieval of documents from a MongoDB database.

During the course of this MongoDB query tutorial, you will see how this function is used in various ways to achieve the purpose of document retrieval.

What is db.collection.find() in MongoDB?

The db.collection.find() method is the primary way to read documents from a MongoDB collection. When you call it without any argument, it returns every document in the collection. When you pass a query object, it returns only the documents that match the given criteria, so you can retrieve exactly the data you need.

The method returns a cursor, which is a pointer to the result set rather than the documents themselves. You usually loop through the cursor to display the results, often with forEach(printjson) to show each document in readable JSON. If you only need a single record, MongoDB also provides findOne(), which returns the first matching document instead of a cursor. Together, find() and findOne() cover most read operations in a MongoDB database, from fetching whole collections to filtering by specific field values.

MongoDB Basic Query Operations

The basic MongoDB query operators cover the simple operations such as getting all of the documents in a MongoDB collection. Let’s look at an db.collection.find example of how we can accomplish this.

All of our code will be run in the MongoDB JavaScript command shell. Consider that we have a collection named ‘Employee’ in our MongoDB database and we execute the below command.

MongoDB Basic Query Operations
MongoDB Basic query operation

Code Explanation:

  1. Employee is the collection name in the MongoDB database
  2. The MongoDB find query is an in-built function which is used to retrieve the documents in the collection.

If the command is executed successfully, the following Output will be shown for the MongoDB find example

Output:

MongoDB Basic Query Operations

The output shows all the documents which are present in the collection.

We can also add criteria to our queries so that we can fetch documents based on certain conditions.

MongoDB Query Example – 1

Let’s look at a couple of MongoDB query examples of how we can accomplish this.

db.Employee.find({EmployeeName : "Smith"}).forEach(printjson);

Code Explanation:

  1. Here we want to find for an Employee whose name is “Smith” in the collection , hence we enter the filter criteria as EmployeeName : “Smith”

If the command is executed successfully, the following Output will be shown

Output:

MongoDB Query Example

The output shows that only the document which contains “Smith” as the Employee Name is returned.

MongoDB Query Example – 2

Now in this MongoDB queries tutorial, let’s take a look at another code example which makes use of the greater than search criteria. When this criteria is included, it actually searches those documents where the value of the field is greater than the specified value.

db.Employee.find({Employeeid : {$gt:2}}).forEach(printjson);

Code Explanation:

  1. Here we want to find for all Employee’s whose id is greater than 2. The $gt is called a query selection operator, and what is just means is to use the greater than expression.

If the MongoDB select fields command is executed successfully, the following Output will be shown

Output:

MongoDB Query Example

All of the documents wherein the Employee id is greater than 2 is returned.

MongoDB Query Operators

MongoDB filters documents using query selection operators inside the find() criteria. These operators let you match ranges, lists, and negations instead of only exact values. The table below lists the most common operators:

Operator Meaning Example
$gt Greater than {Employeeid: {$gt: 2}}
$lt Less than {Employeeid: {$lt: 5}}
$gte Greater than or equal to {age: {$gte: 18}}
$lte Less than or equal to {age: {$lte: 60}}
$ne Not equal to {status: {$ne: “active”}}
$in Matches any value in a list {dept: {$in: [“HR”,”IT”]}}

You can also combine conditions with $and and $or to build more precise queries. Choosing the right operator keeps queries efficient and returns only the documents your application needs.

How to Use Projection with find()

By default, find() returns the entire document, including every field. Often you only need a few fields, such as a name or an id. MongoDB lets you control this with a projection, which is a second argument passed to find() that lists the fields to include or exclude.

To include only specific fields, set them to 1 in the projection object. The following query returns only the EmployeeName field for every document:

db.Employee.find({}, {EmployeeName: 1}).forEach(printjson);

MongoDB always returns the _id field unless you exclude it explicitly. To hide it, set _id to 0:

db.Employee.find({}, {EmployeeName: 1, _id: 0}).forEach(printjson);

You can also exclude fields instead of including them by setting them to 0. For example, the query below returns every field except the Employeeid:

db.Employee.find({}, {Employeeid: 0}).forEach(printjson);

Keep in mind that you cannot mix inclusion and exclusion in the same projection, except for the _id field. Using projection reduces the amount of data transferred from the server, which makes queries faster and responses easier to read, especially on large documents.

FAQs

find() returns a cursor to all documents that match the query, so it can return many results. findOne() returns only the first matching document as a single object, or null if none match.

Chain sort() and limit() to the find() cursor. For example, find().sort({age:1}).limit(5) returns the five youngest records. Use 1 for ascending order and -1 for descending order in sort().

Use countDocuments() with the same filter, for example db.Employee.countDocuments({EmployeeName:”Smith”}). It returns the number of matching documents without retrieving them, which is faster than reading and counting the full result set.

AI can convert a plain-language request into a find() query with the correct operators and projection, and explain each part. Always test the query on sample data before running it in production.

Yes. AI can read a query plan, spot missing indexes or inefficient operators, and suggest indexes or rewritten filters. This helps developers improve find() performance on large collections faster.

Summarize this post with: