From the course: MongoDB Node.js Developer Associate Cert Prep

Querying a MongoDB collection in Node.js applications

From the course: MongoDB Node.js Developer Associate Cert Prep

Querying a MongoDB collection in Node.js applications

- 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 using query operators. The first query that will define uses the accounts collection. Say 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 all the documents in a collection that you 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 the MongoDB collection. Query conditions are expressed as filters by using query operators. In this example, the filter searches for all accounts with a balance of greater than 4700. We use the greater than operator, and we store the 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 use console.log to print out 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 it's value is set to the _id field of the document we're searching for. Next, we'll call the findOne method on the 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 IO, 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 Casper with a balance of $3,373.98. Well done. 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.

Contents