Finding Documents in MongoDB
Introduction
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.
MongoDB Terminology Recap
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.
Two Ways To Extract the Data
MongoDB offers two primary methods to retrieve data from collections:
-
find(): Retrieves multiple documents that match the specified criteria.
-
findOne(): Retrieves a single document that matches the specified criteria, returning the first match it finds.
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.
Finding Multiple Documents
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:
If you want to query for specific documents, you can define a filter. Below you can see a few examples:
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.
