Lesson 3: Querying a MongoDB Collection in Node.js Applications / Learn

Video Transcript (English)

Hello!

In this video, we’ll explore the find() and findOne() methods. These methods are used to retrieve documents from a MongoDB collection in a Node.js application.

We’ll also examine how query predicates allow us to define more efficient queries, or range queries, by using query operators.

The first query that we’ll define uses the accounts collection. Let’s say that we want to find all accounts that have a balance greater than 4700.

We can query for multiple documents in a collection with the collection.find() method. The find() method accepts a query document that matches the documents in the collection that we want to find. In this demonstration, we’ll append the find() method to the accounts collection.

In our application, we have a variable called `accountsCollection` that holds a reference to a MongoDB collection.

Query conditions are expressed as filters by using query operators. In this example, the filter searches for all accounts with a balance greater than 4700. We use the greater than operator, $gt. And, we store this filter in a variable called documentsToFind.

To use this filter in a query, we’ll append the find() method to the accountsCollection and pass the filter, documentsToFind, to the find() method.

If we want to view each document that’s returned from the query, we can iterate by using a loop and then print each document to the terminal.

Finally, we can also use console.log to print the total number of documents found.

In certain cases, we might only want to return a single document from a query. To find a single document, we can use the findOne() method.

Although you can use query operators as part of the filter for findOne(), in this case, we don't need a query operator because we're searching for a specific document that matches the _id.

The filter is within a variable called documentToFind, and its value is set to the _id field of the document we’re searching for.

Next, we’ll call the findOne() method on accountsCollection and pass in the filter, documentToFind.

Remember, all queries that you run in MongoDB should specify a filter to avoid returning all the documents from a collection.

Filtered queries optimize applications’ use of server resources, such as RAM, network, disk I/O, and CPU.

After we run the application by using `node app.js`, a single document is returned. It’s the account for a person named Kasper with a balance of 3373.98.

Great job.

In this video, you learned how to specify and filter queries when finding documents in MongoDB.

We used find() to find multiple documents and findOne() to find a single document. We also used query operators, such as $gt, to help refine our search for documents within a collection.