Write Basic MongoDB Queries

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to write basic MongoDB queries, including finding all documents, performing exact matches, using query operators, selecting specific fields, and formatting query output. You will start by retrieving all documents from a MongoDB collection using the find() method, then move on to more advanced techniques such as querying for exact matches, utilizing query operators, and customizing the output. By the end of this lab, you will have a solid understanding of the fundamental skills required for working with MongoDB databases.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb/BasicOperationsGroup -.-> mongodb/start_mongodb_shell("`Start MongoDB Shell`") mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/QueryOperationsGroup -.-> mongodb/sort_documents("`Sort Documents`") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("`Project Fields`") mongodb/DataTypesGroup -.-> mongodb/use_numeric_data_types("`Use Numeric Data Types`") subgraph Lab Skills mongodb/start_mongodb_shell -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/create_database_collection -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/find_documents -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/query_with_conditions -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/sort_documents -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/project_fields -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} mongodb/use_numeric_data_types -.-> lab-420824{{"`Write Basic MongoDB Queries`"}} end

Find All Documents

In this step, you'll learn how to retrieve all documents from a MongoDB collection using the find() method. This is a fundamental skill for working with MongoDB databases.

First, let's start the MongoDB shell and create a sample database with some documents to work with:

mongosh

Once in the MongoDB shell, create a new database and add some sample data:

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

Now, to find all documents in the books collection, use the find() method without any parameters:

db.books.find();

You should see output similar to this:

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

Let's break down what happened:

  • use bookstore creates or switches to the bookstore database
  • db.books.insertMany() adds multiple documents to the books collection
  • db.books.find() retrieves all documents in the collection

If you want a more readable output, you can use pretty():

db.books.find().pretty();

This will format the output with line breaks and indentation, making it easier to read.

Query Exact Matches

In this step, you'll learn how to perform exact matches in MongoDB queries. Building on the previous step, we'll continue using our bookstore database to demonstrate precise document retrieval.

First, ensure you're in the MongoDB shell and using the bookstore database:

use bookstore

To find documents with an exact match for a specific field, you'll use the find() method with a query object. Let's find a book by its exact title:

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

This query will return only the document where the title exactly matches "Python Basics". You should see output like:

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

Now, let's try an exact match on another field - the author:

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

You can also combine multiple exact match conditions to narrow down your search:

db.books.find({
  title: "MongoDB Essentials",
  author: "Jane Doe"
});

This query will return documents that match both the title and author exactly.

Let's explore another example with the year field:

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

Important notes about exact matches:

  • The match is case-sensitive
  • The entire field must match exactly
  • The order and exact spelling matter

If you want to see how many documents match your query, use countDocuments():

db.books.countDocuments({ year: 2022 });

Use Query Operators

In this step, you'll learn how to use MongoDB query operators to perform more complex and flexible queries. Query operators allow you to create more advanced filters beyond exact matches.

First, ensure you're in the MongoDB shell using the bookstore database:

use bookstore

Let's add a few more books to our collection to demonstrate different operators:

db.books.insertMany([
  { title: "Advanced Python", author: "John Smith", year: 2020, price: 39.99 },
  {
    title: "Data Science Handbook",
    author: "Jane Doe",
    year: 2019,
    price: 45.5
  },
  {
    title: "Machine Learning Basics",
    author: "Alice Johnson",
    year: 2021,
    price: 55.25
  }
]);

Now, let's explore some common query operators:

  1. Greater Than ($gt) and Less Than ($lt) Operators:
    Find books published after 2020:
db.books.find({ year: { $gt: 2020 } });

Find books published before 2020:

db.books.find({ year: { $lt: 2020 } });
  1. Greater Than or Equal To ($gte) and Less Than or Equal To ($lte) Operators:
    Find books published in or after 2020:
db.books.find({ year: { $gte: 2020 } });
  1. Not Equal ($ne) Operator:
    Find books not written by John Smith:
db.books.find({ author: { $ne: "John Smith" } });
  1. In ($in) Operator:
    Find books by specific authors:
db.books.find({ author: { $in: ["John Smith", "Jane Doe"] } });
  1. Not In ($nin) Operator:
    Find books not by these authors:
db.books.find({ author: { $nin: ["John Smith", "Jane Doe"] } });
  1. Multiple Conditions:
    Combine operators for more complex queries:
db.books.find({
  year: { $gte: 2020 },
  price: { $lt: 50 }
});

This query finds books published in or after 2020 with a price less than 50.

Select Specific Fields

In this step, you'll learn how to select and project only specific fields from your MongoDB documents. This is useful when you want to retrieve only the information you need, reducing data transfer and improving query performance.

First, ensure you're in the MongoDB shell using the bookstore database:

use bookstore
  1. Select Specific Fields:
    To select only certain fields, use the second argument in the find() method:
db.books.find({}, { title: 1, author: 1, _id: 0 });

Breaking down the query:

  • First argument {} means no filter (select all documents)
  • Second argument specifies which fields to include
  • 1 means include the field
  • _id: 0 explicitly excludes the default _id field

You should see output like:

[
  { title: 'Python Basics', author: 'John Smith' },
  { title: 'MongoDB Essentials', author: 'Jane Doe' },
  ...
]
  1. Combine Field Selection with Filtering:
    You can combine field selection with query conditions:
db.books.find({ year: { $gt: 2020 } }, { title: 1, year: 1, _id: 0 });

This query finds books published after 2020 and returns only their titles and years.

  1. Excluding Fields:
    You can also exclude specific fields:
db.books.find({}, { price: 0 });

This returns all fields except the price field.

  1. Projecting Nested Fields:
    If you have nested documents, you can select specific nested fields:
// Assuming a more complex document structure
db.books.find({}, { "author.name": 1, title: 1, _id: 0 });

Important Notes:

  • You can't mix inclusion and exclusion in a single projection (except for _id)
  • _id is included by default unless explicitly set to 0
  • Projections help reduce the amount of data transferred

Format Query Output

In this step, you'll learn how to format and manipulate the output of your MongoDB queries, making your results more readable and useful.

First, ensure you're in the MongoDB shell using the bookstore database:

use bookstore
  1. Pretty Printing:
    Use .pretty() to format the output with indentation:
db.books.find().pretty();
  1. Limiting Results:
    Use .limit() to restrict the number of documents returned:
db.books.find().limit(2);
  1. Sorting Results:
    Use .sort() to order your documents. The argument is an object specifying the field and sort direction:
// Sort by year in ascending order
db.books.find().sort({ year: 1 });

// Sort by year in descending order
db.books.find().sort({ year: -1 });
  1. Combining Methods:
    You can chain multiple formatting methods:
db.books
  .find()
  .sort({ year: -1 }) // Sort by year descending
  .limit(3) // Get top 3 results
  .pretty(); // Format nicely
  1. Skip Documents:
    Use .skip() to skip a specified number of documents:
// Skip first 2 documents
db.books.find().skip(2).limit(2);
  1. Count Documents:
    Use .count() or countDocuments() to get the total number of matching documents:
// Count all books
db.books.countDocuments();

// Count books published after 2020
db.books.countDocuments({ year: { $gt: 2020 } });

Practical Example:
Let's combine multiple formatting techniques:

db.books
  .find({ year: { $gte: 2020 } })
  .sort({ price: 1 }) // Sort by price ascending
  .limit(2) // Get 2 cheapest books after 2020
  .pretty();

Summary

In this lab, you will learn how to perform basic MongoDB queries, including finding all documents in a collection, querying for exact matches, using query operators, selecting specific fields, and formatting the query output. You will start by learning how to retrieve all documents from a MongoDB collection using the find() method, which is a fundamental skill for working with MongoDB databases. Then, you will explore how to perform exact matches in MongoDB queries, allowing you to retrieve documents with specific field values. Throughout the lab, you will gain a solid understanding of the essential MongoDB querying techniques.

Other MongoDB Tutorials you may like