Use MongoDB Basic Types

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to work with various fundamental data types in MongoDB. The lab covers practical examples of how to store, query, and manipulate data using numbers, strings, booleans, dates, and ObjectIds. You will gain hands-on experience performing common database operations and understanding the appropriate use cases for each data type. By the end of this lab, you will have a solid foundation for modeling data effectively in MongoDB.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 83% positive review rate from learners.

Working with Numbers and Strings

In this first step, you will learn to use the most common data types: numbers and strings. You will start the MongoDB shell, create a database and collection, and then insert and query documents containing these types.

First, open your terminal and launch the MongoDB shell. This interactive environment allows you to execute commands directly against your database.

mongosh

Once inside the shell, you will see a > prompt. Let's create and switch to a new database named inventory. In MongoDB, a database is created automatically when you first store data in it.

use inventory

Now, create a collection named products and insert a document. This document will contain a string field (name) and two number fields (price and stock). MongoDB uses BSON (Binary JSON) types, where numbers can be integers or floating-point numbers (doubles).

db.products.insertOne({
    name: "Laptop",
    price: 1200.50,
    stock: 50
})

You should see a confirmation message with the ObjectId of the newly inserted document.

Example Output:

{
  "acknowledged": true,
  "insertedId": ObjectId("...")
}

Now that the document is inserted, let's query the collection. First, find products with a price greater than 1000 using the $gt (greater than) operator.

db.products.find({ price: { $gt: 1000 } })

Example Output:

[
  {
    _id: ObjectId("..."),
    name: 'Laptop',
    price: 1200.5,
    stock: 50
  }
]

Next, perform a query to find a product by its exact name, which is a string value. This is a common way to retrieve specific items.

db.products.find({ name: "Laptop" })

This command will return the same document, demonstrating how to query based on string fields.

Using Booleans and Null Values

In this step, you will explore boolean and null data types. Booleans are ideal for fields that represent a true or false state, such as flags. The null type is used to represent a field with no value.

Let's continue using the inventory database in the mongosh shell. Insert a new product with boolean fields inStock and onSale, and a discontinuedDate field set to null.

db.products.insertOne({
    name: "Wireless Mouse",
    price: 25,
    inStock: true,
    onSale: false,
    discontinuedDate: null
})

Example Output:

{
  "acknowledged": true,
  "insertedId": ObjectId("...")
}

Now you have a document with boolean and null values. You can query for these just like any other data type. Let's find all products that are currently in stock by querying for the boolean value true.

db.products.find({ inStock: true })

Example Output:

[
  {
    _id: ObjectId("..."),
    name: 'Wireless Mouse',
    price: 25,
    inStock: true,
    onSale: false,
    discontinuedDate: null
  }
]

This command retrieves documents where the inStock field is exactly true. Next, let's find products that have not been discontinued by looking for a null value in the discontinuedDate field. Note that in MongoDB, querying for null matches both documents where the field is explicitly set to null and documents where the field doesn't exist at all.

db.products.find({ discontinuedDate: null })

This query will return multiple documents: the "Wireless Mouse" (which has discontinuedDate: null) and any other products that don't have a discontinuedDate field at all (like "Laptop"). If you want to find only documents where the field is explicitly set to null, you would need to use a different query pattern.

Storing Dates and Timestamps

This step focuses on the Date data type, which is essential for storing time-based information like creation dates, updates, or events. MongoDB stores dates as 64-bit integers representing milliseconds since the Unix epoch (Jan 1, 1970, UTC).

Let's insert a document with date fields. You can create a date object for the current time using new Date() or for a specific time by passing an ISO-8601 date string.

db.products.insertOne({
    name: "Smartwatch",
    price: 250,
    purchaseDate: new Date("2023-10-26T10:00:00Z"),
    lastUpdated: new Date()
})

Example Output:

{
  "acknowledged": true,
  "insertedId": ObjectId("...")
}

Now, let's query for products based on their date fields. For example, find all products purchased on or after the beginning of 2023. You can use the $gte (greater than or equal to) operator with a Date object.

db.products.find({
    purchaseDate: { $gte: new Date("2023-01-01") }
})

Example Output:

[
  {
    _id: ObjectId("..."),
    name: 'Smartwatch',
    price: 250,
    purchaseDate: ISODate('2023-10-26T10:00:00.000Z'),
    lastUpdated: ISODate('...')
  }
]

MongoDB also provides update operators for dates. The $currentDate operator is useful for setting a field to the current server date. Let's update the lastUpdated field for the "Laptop" document you created earlier to track when it was last modified.

db.products.updateOne(
    { name: "Laptop" },
    { $currentDate: { lastUpdated: true } }
)

Example Output:

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": 1,
  "modifiedCount": 1,
  "upsertedCount": 0
}

This operation finds the document with the name "Laptop" and updates its lastUpdated field to the current timestamp.

Understanding ObjectIds and Arrays

In this final step, you will learn about two important structural types: ObjectId and Array. Every document in MongoDB has a unique _id field, which defaults to an ObjectId if not provided. Arrays allow you to store lists of values within a single field.

First, let's insert a document with an array field named tags. This is useful for storing multiple categories or attributes.

db.products.insertOne({
    name: "Mechanical Keyboard",
    price: 75,
    tags: ["gaming", "mechanical", "RGB"]
})

Example Output:

{
  "acknowledged": true,
  "insertedId": ObjectId("...")
}

The insertedId is the ObjectId for this new document. It is a 12-byte value that guarantees uniqueness. You can query for a document by its _id. First, find the document and store its _id in a variable.

const keyboard = db.products.findOne({ name: "Mechanical Keyboard" })
const keyboardId = keyboard._id

Now, use this keyboardId variable to fetch the document again. This is the most efficient way to retrieve a single, specific document.

db.products.findOne({ _id: keyboardId })

Next, let's work with the tags array. You can query for documents where the array contains a specific element. For example, to find all products tagged with "gaming":

db.products.find({ tags: "gaming" })

Example Output:

[
  {
    _id: ObjectId("..."),
    name: 'Mechanical Keyboard',
    price: 75,
    tags: [ 'gaming', 'mechanical', 'RGB' ]
  }
]

This command efficiently finds all documents where the tags array includes the string "gaming". Arrays are a powerful feature for modeling relationships within a single document. To exit the MongoDB shell, type exit or press Ctrl+D.

exit

Summary

In this lab, you have learned how to work with the most essential data types in MongoDB. You started by using numbers and strings to store and query product information. You then explored booleans and the null value for representing status flags and missing data. You also learned to handle temporal data using the Date type and its associated operators. Finally, you gained an understanding of the ObjectId as a unique identifier and the Array type for storing lists of values. This knowledge provides a strong foundation for designing and interacting with MongoDB databases for a wide range of applications.