Write Basic MongoDB Queries

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn essential MongoDB query techniques. You will start by connecting to a database and inserting data. Then, you will practice retrieving documents, filtering them with exact matches and comparison operators, selecting specific fields to return, and formatting the output by sorting and limiting results. By the end of this lab, you will have a solid foundation for querying data in a MongoDB database.

Connect to MongoDB and Find All Documents

In this first step, you will connect to the MongoDB server, create a database and a collection, insert some sample data, and then retrieve all the documents from that collection. This is the starting point for any database interaction.

First, open your terminal and start the MongoDB Shell by running the mongosh command.

mongosh

Your terminal prompt will change to indicate that you are now inside the MongoDB Shell, ready to execute database commands.

Next, switch to a new database named bookstore. If the database does not exist, MongoDB will create it when you first store data.

use bookstore

Now, let's insert some documents into a new collection called books. A collection is a group of MongoDB documents, similar to a table in a relational database. The insertMany() method allows you to add multiple documents at once.

db.books.insertMany([
  { title: "Python Basics", author: "John Smith", year: 2022, stock: 15 },
  { title: "MongoDB Essentials", author: "Jane Doe", year: 2023, stock: 8 },
  { title: "Web Development", author: "Alice Johnson", year: 2021, stock: 20 }
]);

After executing the command, you will see a confirmation that the documents were successfully inserted.

To retrieve and view all documents in the books collection, use the find() method without any arguments.

db.books.find();

The output will list all three documents you just inserted. Each document has an _id field, which is a unique identifier automatically added by MongoDB.

[
  {
    _id: ObjectId("..."),
    title: 'Python Basics',
    author: 'John Smith',
    year: 2022,
    stock: 15
  },
  {
    _id: ObjectId("..."),
    title: 'MongoDB Essentials',
    author: 'Jane Doe',
    year: 2023,
    stock: 8
  },
  {
    _id: ObjectId("..."),
    title: 'Web Development',
    author: 'Alice Johnson',
    year: 2021,
    stock: 20
  }
]

Query for Documents with Exact Matches

Now that you can retrieve all documents, the next step is to filter them to find specific ones. You can do this by providing a query filter document to the find() method. This allows you to perform exact matches on field values.

Let's find the book with the exact title "Python Basics". The query filter { title: "Python Basics" } tells MongoDB to return only the documents where the title field is exactly "Python Basics".

db.books.find({ title: "Python Basics" });

The command will return only the one document that matches the criteria:

[
  {
    _id: ObjectId("..."),
    title: 'Python Basics',
    author: 'John Smith',
    year: 2022,
    stock: 15
  }
]

You can also query based on other fields, such as numbers. For example, to find all books published in the year 2021:

db.books.find({ year: 2021 });

To create a more specific query, you can specify multiple fields in the filter document. This creates an implicit "AND" condition, meaning all specified conditions must be true for a document to be returned. Let's find a book written by "Jane Doe" AND published in 2023.

db.books.find({ author: "Jane Doe", year: 2023 });

This query will return the "MongoDB Essentials" book, as it is the only one that matches both the author and the year.

Filter with Comparison Operators

Exact matches are useful, but often you need to find documents based on comparisons, such as finding all books published after a certain year or with stock above a certain level. MongoDB provides a set of query operators for this purpose.

Comparison operators are specified within the query document using a syntax like { field: { $operator: value } }.

Let's find all books published after 2021. We will use the "greater than" operator, $gt.

db.books.find({ year: { $gt: 2021 } });

This will return "Python Basics" (2022) and "MongoDB Essentials" (2023).

Here are some other common comparison operators:

  • $lt: less than
  • $gte: greater than or equal to
  • $lte: less than or equal to
  • $ne: not equal to

For example, to find all books with a stock of 15 or less, you can use the $lte operator.

db.books.find({ stock: { $lte: 15 } });

Another useful operator is $in, which matches any of the values specified in an array. Let's find all books written by either "John Smith" or "Alice Johnson".

db.books.find({ author: { $in: ["John Smith", "Alice Johnson"] } });

This query will return "Python Basics" and "Web Development". You can combine operators with exact matches to build more complex queries. For instance, find books published in or after 2022 with a stock of less than 20.

db.books.find({ year: { $gte: 2022 }, stock: { $lt: 20 } });

Select Specific Fields to Return (Projection)

By default, MongoDB queries return all fields in matching documents. To improve performance and make the output cleaner, you can specify which fields to return. This is called projection.

Projection is handled by the second argument in the find() method. This argument is a document where you specify the fields to include with a 1 or exclude with a 0.

Let's retrieve all books but only return their title and author fields. The first argument, {}, is an empty filter, which matches all documents.

db.books.find({}, { title: 1, author: 1 });

You will notice the _id field is still included in the output. The _id field is always returned by default. To exclude it, you must explicitly set it to 0.

db.books.find({}, { title: 1, author: 1, _id: 0 });

Now the output will be much cleaner, containing only the requested fields:

[
  { "title": "Python Basics", "author": "John Smith" },
  { "title": "MongoDB Essentials", "author": "Jane Doe" },
  { "title": "Web Development", "author": "Alice Johnson" }
]

You can combine a query filter with a projection. For example, let's find books published in 2023 and return only their titles.

db.books.find({ year: 2023 }, { title: 1, _id: 0 });

This powerful feature allows you to tailor the query results to exactly what your application needs, reducing unnecessary data transfer.

Sort, Skip, and Limit Results

Often, you need to control the order and quantity of the results returned by a query. MongoDB provides cursor methods that you can chain onto a find() query to sort, skip, and limit the documents in the result set.

To sort the results, use the .sort() method. It takes a document specifying the field to sort by and the direction: 1 for ascending and -1 for descending. Let's sort the books by year in descending order (newest first).

db.books.find().sort({ year: -1 });

To limit the number of documents returned, use the .limit() method. For example, to get only the top 2 newest books:

db.books.find().sort({ year: -1 }).limit(2);

The .skip() method is used to bypass a specified number of documents from the beginning of the result set. This is useful for implementing pagination. Let's retrieve all books, but skip the first one.

db.books.find().sort({ year: 1 }).skip(1);

You can chain these methods together to create powerful and precise queries. For example, to find the second oldest book in the collection, you can sort by year ascending, skip the first result, and limit the output to one.

db.books.find().sort({ year: 1 }).skip(1).limit(1);

This command will return the "Python Basics" book, which was published in 2022.

Finally, to exit the MongoDB shell, type exit or press Ctrl+D.

exit;

Summary

In this lab, you have learned the fundamentals of writing basic queries in MongoDB. You started by connecting to a database with the mongosh shell and inserting documents into a collection. You then practiced retrieving documents using find(), filtering results with exact matches and comparison operators like $gt and $in, and using projection to select specific fields. Finally, you learned how to format the output by chaining cursor methods like .sort(), .limit(), and .skip() to control the order and size of your result set. These skills form the foundation for interacting with and managing data in MongoDB.