MongoDB Find Command To Query Documents

In this article, we will learn about MongoDB Find command. This command is used to query the documents available in the collection. This is similar to the ‘select’ statement in the relational databases. As in SQL, we can use various options with ‘select’ statement to retrieve the data, here in MongoDB also, Find command provides various option/properties to fetch the required data.

You can read RDBMS vs MongoDB to understand better.

MongoDB Find Command


I will explain a few options provided by Find method with the examples and code in this article. We will learn other options in the subsequent articles. Let’s start with this.

To query data from the MongoDB collections, we need to use MongoDB’s find() method.

Syntax

The basic syntax of the find() method is as follows –

db.COLLECTION_NAME.find()

The db.collection.find() method reads operations in Mongo shell and retrieves documents that match containing all their fields.

This find() method contains a filter which is nothing but condition or criteria for which it fetches the records from the collections. If you want to select all the documents from the collection, use find()  (i.e. without any filter or empty document) or put the query document ({}) empty such as:

db.COLLECTION_NAME.find({}); // or db.COLLECTION_NAME.find();

For example:

I have started the MongoDB database. Below are the various databases available in my system. I am choosing ‘mohit’ database first.

Under this ‘mohit’ database, you can see there is a number of collections available, each containing a number of records.

> show dbs
admin 0.000GB
blog 0.011GB
enron 0.211GB
local 0.000GB
m101 0.000GB
mohit 0.017GB
school 0.000GB
students 0.000GB
test 0.002GB
video 0.001GB
week5 0.002GB
> show collections
TutorialsJar
albums
counting
images
info
mohit
posts
>

Here, I am choosing ‘images’ to explain the working of find() method.

Below is the query, I wrote:

db.images.find();

Output:

MongoDB Find Command

The result set contains all documents in the images collection.

Note: This find method returns all the documents in a non-structured way. You can see in the above snapshot.

If you want the data to be retrieved in the formatted and easily understandable way, you can use pretty() method. As the name suggests, it presents the data in a pretty way. You just need to append pretty() method to find() method.

Syntax:

db.COLLECTION_NAME.find().pretty()

MongoDB Find Command with Pretty

There is another variation of find() method provided by MongoDB. If you want to retrieve just ONLY ONE document from the given collection, use findOne() method. It returns only one document. This method is useful when you just want to get the hint of the records/documents presented in the collection.

Syntax:

db.COLLECTION_NAME.findOne()

Example:

> db.images.findOne();

{

        "_id" : 0,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "work"

        ]

}

>

Note: FindOne() method by default includes the Pretty(). It shows the output in the formatted way only.

Using Find() methods, you can search in the embedded document also using dot (.) operator.

The find() function in mongo shell returns query results in a cursor, which is an iterable object that yields documents. However, in the mongo shell, if the returned cursor is not assigned to a variable using the ‘var’ keyword, then the cursor is automatically iterated up to 20 times. Hence, it prints up to the first 20 documents in the results.

You can manually iterate the cursor in the mongo shell using the cursor method next() to access the documents, as in the following example:

var myCursor = db.users.find();

while (myCursor.hasNext()) {
   print(myCursor.next());
}

 

Below is the list of various options we can use with find() method which we can use to return desired results from mongo server (or shell)

MongoDB Find Command with Limit Method


MongoDB provides a very easy way to limit the results being fetched from the collections using limit() method. For example, if you want to retrieve ONLY ONE record from the collection, you can use Find() with limit(1) instead of using FindOne() method.

Syntax:

db.COLLECTION_NAME.find().limit();

Example:

Below is the example to fetch only one document from the ‘images’ collection.

> db.images.find().limit(1);

{ "_id" : 0, "height" : 480, "width" : 640, "tags" : [ "dogs", "work" ] }

>

Here, you can see that I had put the limit(1) to fetch only one record and it is showing the same output as shown in the case of FindOne(). The only difference is that the output is not in a formatted way because find() does not include Pretty() by default.

MongoDB Find Command With Filter


Let’s see one example where we are using the filter to fetch the document from the collection.

Syntax:

db.COLLECTION_NAME.find(filter);

In the below query, I am putting a filter(equal operator) on find() method to fetch the single document where _id=18. (i.e. key-value pair, where the key is _id and value is 18) (_id is overridden objectid)

> db.images.find({"_id":18}).pretty();

{

        "_id" : 18,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens",

                "vacation",

                "work"

        ]

}

>

Here, pretty() is optional. I am using pretty() just to format the fetched record.

The above example shows the equality match filter. We will learn more about other MongoDB query operators in upcoming sections.

Find Command with SKIP Method


In MongoDB, apart from putting the limit on results to be fetched, you can also use skip() method to skip the first few documents.

Syntax:

db.COLLECTION_NAME.find().skip();

In below example, I am using skip(5) to skip the first 5 documents from the collection and fetch all the documents from the collection after that. Here, it has returned all the documents after skipping first five documents.

> db.images.find().skip(5).pretty();

{

        "_id" : 5,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens",

                "work"

        ]

}

{ "_id" : 6, "height" : 480, "width" : 640, "tags" : [ "work" ] }

{

        "_id" : 7,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "sunrises"

        ]

}

{

        "_id" : 8,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens",

                "travel"

        ]

}

{

        "_id" : 9,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "sunrises",

                "travel"

        ]

}

{

        "_id" : 10,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "cats",

                "kittens",

                "travel",

                "vacation",

                "work"

        ]

}

{

        "_id" : 11,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "cats",

                "travel"

        ]

}

{

        "_id" : 12,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "travel"

        ]

}

{

        "_id" : 13,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens"

        ]

}

{

        "_id" : 14,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "sunrises",

                "vacation"

        ]

}

{

        "_id" : 15,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "travel",

                "vacation",

                "work"

        ]

}

{

        "_id" : 16,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "cats",

                "vacation"

        ]

}

{

        "_id" : 17,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "kittens",

                "vacation",

                "work"

        ]

}

{

        "_id" : 18,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens",

                "vacation",

                "work"

        ]

}

{

        "_id" : 19,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "sunrises",

                "kittens",

                "travel",

                "work"

        ]

}

{

        "_id" : 20,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "sunrises",

                "kittens"

        ]

}

{

        "_id" : 21,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "travel",

                "vacation"

        ]

}

{

        "_id" : 22,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "sunrises",

                "travel",

                "vacation",

                "work"

        ]

}

{

        "_id" : 23,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "cats",

                "kittens",

                "travel"

        ]

}

{

        "_id" : 24,

        "height" : 480,

        "width" : 640,

        "tags" : [

                "dogs",

                "cats",

                "sunrises",

                "kittens",

                "travel",

                "vacation"

        ]

}

Type "it" for more

>

Find Command with SKIP () & LIMIT()


You can also use limit() with skip() here. It will make the normal collection call and will skip elements first and then limit.

Syntax:

db.COLLECTION_NAME.find().skip().limit();

Example: Here, I am fetching only 2 documents after skipping the first 5 documents.

> db.images.find().skip(5).limit(2).pretty();
{
"_id" : 5,
"height" : 480,
"width" : 640,
"tags" : [
"dogs",
"cats",
"sunrises",
"kittens",
"work"
]
}
{ "_id" : 6, "height" : 480, "width" : 640, "tags" : [ "work" ] }
>

Find Command with SORT() Method


You can also sort the results with any field in ascending or descending orders.

Syntax:

db.COLLECTION_NAME.find().sort().pretty();

Example:

In below example, I am sorting the results in descending order of _id.

Key point:    To sort in ascending order: Use 1 with the field.

                       To sort in descending order: Use -1 with the field.

MongoDB Find Command with Sort

You can see that documents are being fetched in descending order of _id.

Note: You can also use skip(), limit() methods with sort(). Find one such example below:

> db.images.find().sort({"_id":-1}).skip(5).limit(4).pretty();
{ "_id" : 99994, "height" : 480, "width" : 640, "tags" : [ "travel" ] }
{
"_id" : 99993,
"height" : 480,
"width" : 640,
"tags" : [
"cats",
"sunrises",
"travel",
"vacation",
"work"
]
}
{
"_id" : 99992,
"height" : 480,
"width" : 640,
"tags" : [
"cats",
"sunrises",
"travel"
]
}
{
"_id" : 99991,
"height" : 480,
"width" : 640,
"tags" : [
"dogs",
"cats",
"kittens",
"vacation",
"work"
]
}
>

Here, I am first sorting the _id field in the descending order (i.e. -1) and then skipping first 5 documents and then limiting the results to be fetched to 4.

That’s all in this MongoDB Find Command article. I hope you like this article and it helped you to understand the concept in a better way. In the upcoming articles, we will discuss MongoDB Projection (excludes the id, include/exclude any field) concept and various other operators (such as comparison operators, logical operators, array operators etc.) available in MongoDB. We will also see how these have made using MongoDB easy to a greater extent.

Do share your feedback in the comment section below. Do not forget to subscribe to our blog for further updates and share this article with your friends and colleagues.

Mohit Arora
Follow me