Hello there! This lesson covers an essential aspect of working with MongoDB: retrieving or "finding" documents from MongoDB collections. Database functionality revolves around the ability to store and retrieve data. Without efficient data retrieval, a database would lose much of its utility. Let’s dive into MongoDB's data retrieval mechanisms.
Before diving into data retrieval, let’s recap some essential MongoDB terminology:
- Documents: The basic units of data in MongoDB, akin to a row in relational databases. They are stored in BSON (Binary JSON) format.
- Collections: Groups of documents, similar to tables in relational databases.
- Databases: Containers for collections. A single MongoDB server can host multiple databases.
For instance, if you want to retrieve data about books, such as titles or authors, you would focus on the books
collection in the books_db
database.
MongoDB offers two primary methods to retrieve data from collections:
-
find(): Retrieves multiple documents that match the specified criteria.
1db.collection.find(query, projection, options)
-
findOne(): Retrieves a single document that matches the specified criteria, returning the first match it finds.
1db.collection.findOne(query, projection, options)
In this course, we'll focus on writing simple find
queries using the query
parameter. The projection
and options
parameters are optional and provide additional functionality, which will be covered later in the course path.
As mentioned above, using the find()
method, you can extract multiple documents from a collection. The code below extracts all the documents from the books
collection without any filtering criteria:
JavaScript1use library_db 2 3db.books.find()
If you want to query for specific documents, you can define a filter. Below you can see a few examples:
JavaScript1use library_db 2 3// Retrieve all documents with the genre 'Adventure' from the "books" collection 4db.books.find({ "genre": "Adventure" }) 5 6// Retrieve all documents with the author 'J.K. Rowling' from the "books" collection 7db.books.find({ "author": "J.K. Rowling" }) 8 9// Retrieve all documents with the publication year 2020 from the "books" collection 10db.books.find({ "publication_year": 2020 }) 11 12// Retrieve all documents from the "books" collection with an empty filter 13db.books.find({})
Filters in MongoDB are specified in a JSON-like format. In this format, the keys represent field names, and the values represent the criteria those fields must meet.
For example:
{ "genre": "Adventure" }
fetches all documents where the genre field is "Adventure".- More complex filters can involve multiple fields. For instance,
{ "genre": "Adventure", "publication_year": 2020 }
retrieves documents where both criteria are satisfied.
Filters can become highly sophisticated, incorporating operators and nested conditions, which will be explored in greater detail later in the course path.
The find()
method always returns a cursor object — an iterable object that enables you to process each document in the result set individually. This mechanism allows MongoDB to load data lazily, optimizing memory usage and performance. You can use the .toArray()
method to exhaust the cursor and get all results. Be careful, though, as doing so can cause your application to run out of memory:
JavaScript1use library_db 2 3db.books.find({ "genre": "Adventure" }).toArray()
The findOne()
method simplifies retrieving a single document that matches the criteria. Its syntax is very similar to find()
, with the only difference being that this method returns the first matching document it finds. Below are a few examples:
JavaScript1use library_db 2 3// Retrieve and print one document from the "books" collection 4db.books.findOne() 5 6// Retrieve and print one document with the genre 'Adventure' from the "books" collection 7db.books.findOne({ "genre": "Adventure" }) 8 9// Retrieve and print one document with the author 'J.K. Rowling' from the "books" collection 10db.books.findOne({ "author": "J.K. Rowling" })
To make the output more readable when working in the MongoDB shell, you can use the .pretty()
method. This method formats the output in a more structured and readable manner.
Here's an example:
JavaScript1use library_db 2 3// Retrieve all documents with the genre 'Adventure' from the "books" collection and format the output 4db.books.find({ "genre": "Adventure" }).pretty()
For the findOne()
method, pretty printing is not necessary as it formats the output by default.
In this lesson, we covered MongoDB's data retrieval mechanisms. You learned how to use the find()
method to retrieve multiple documents and the findOne()
method to retrieve a single document from a collection. We also delved into understanding the cursor object for handling large result sets. Additionally, we discussed pretty printing for more readable output. Get ready to practice these concepts in the upcoming exercises!