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.