Query options in MongoDB
1. Query options in MongoDB
Welcome back! In this video, you’ll learn how to control and customize the data MongoDB returns—so you get exactly what you need, and nothing more.2. Limiting the number of results
Remember that word of warning from the first chapter? Calling .find() without any arguments returns all documents. It's just 41 in our case, but it could be much more and imply gigabytes of data in a real-world setting. You can narrow things down with filters, but there’s another useful tool: .limit(). When you add .limit(5) to a .find() call like this, you get a cursor that only points to the first 5 matching documents. Using .limit() is a great way to test a query safely, without risking a flood of results.3. Sorting in ascending and descending order
Next up: sorting, or controlling the order in which the result of your query is returned. To sort the results of a .find() query, just chain on .sort(). As you can see in this example, it takes two arguments: First, the field you want to sort by; in this case, that's "title". The second argument is the sort direction: 1 for ascending (A–Z or low to high) -1 for descending (Z–A or high to low) In the example on the right, we're sorting by release year in descending order. Indeed, the most recently released movie is showing on top.4. Counting matching documents
Sometimes, you don’t need the full documents— you just want to know how many match a condition. For example: How many movies are in the "Action" genre? One way to do that is by using .find() and wrapping it in list() to count the results: 16. But that’s not very efficient, especially for large datasets. A better way is to use .count_documents(). You pass in the same filter you’d use with .find(), and MongoDB returns the total number of matching documents without fetching all the data. It’s faster and cleaner.5. Using projection to shape your results
By default, MongoDB returns all fields in each document. But often, we only care about a few—like the title or rating of a movie. That’s where projection comes in. It lets you control exactly which fields are returned. You pass a second argument to .find()—a dictionary listing the fields you want, each set to 1. The first argument you see is an empty filter. Even if you're not filtering anything, it still needs to be there—just as a placeholder. It turns out that MongoDB includes the _id field by default—even if it’s not in your projection. That's an exception. To leave it out, you have to explicitly set the "_id" key to 0. Using projection, you can get exactly the fields you want—and nothing extra.6. Let's practice!
We’ve seen how to limit, sort, count, and control which fields are returned. Now it’s your turn to practice!Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.