Objectives:
Familiarize yourself with fundamental MongoDB concepts and operations.
Practice creating and managing databases, collections, documents, and data types.
Perform basic CRUD (Create, Read, Update, Delete) operations on documents.
Utilize sorting, limiting, comparison, and logical operators in queries.
Understand the role of indexes in optimizing queries.
Prerequisites:
Basic understanding of database concepts.
MongoDB installed and running on your system
(https://www.mongodb.com/try/download/community).
A terminal or command prompt for interacting with MongoDB Shell.
Steps:
1. Create Databases:
o Open the MongoDB Shell using mongo.
o Create two databases named myDatabase1 and myDatabase2 using use
<database_name>.
Bash
mongo
use myDatabase1
use myDatabase2
db.createCollection("products")
2. Insert Documents:
o Insert documents into each database using the
db.<collection_name>.insertOne(<document>) or
db.<collection_name>.insertMany([<document1>, <document2>,
...]) methods.
o Include documents with various data types (strings, numbers, booleans, arrays,
embedded documents) for practice.
// Example document
var product = {
name: "Laptop",
price: 799.99,
inStock: true,
categories: ["Electronics", "Laptops"],
details: {
brand: "Acme",
model: "Xtreme-15"
}
}
// Insert into myDatabase1.products collection
db.products.insertOne(product)
// Insert multiple documents into myDatabase2.books collection
var books = [
{ title: "The Lord of the Rings", author: "J.R.R. Tolkien" },
{ title: "Pride and Prejudice", author: "Jane Austen", year: 1813
}
]
db.books.insertMany(books)
3. Explore Data Types:
o Use the db.<collection_name>.find() method to retrieve documents.
o Access specific fields using dot notation (e.g., product.name) or by explicitly
specifying the field name.
o Observe how different data types are stored and represented.
Bash
// Find all products in myDatabase1
db.products.find()
// Find books with title containing "Pride" (case-insensitive)
db.books.find({ title: /Pride/i })
4. Sort and Limit Results:
o Sort documents based on specific fields using the sort parameter within
db.<collection_name>.find().
o Use ascending (1) or descending (-1) order for sorting.
o Apply the limit parameter to restrict the number of returned documents.
Bash
// Sort books by title (ascending) and limit to 2 results
db.books.find().sort({ title: 1 }).limit(2)
5. Filtering Data with find:
o Utilize comparison operators ($eq, $gt, $lt, $ne, etc.) to filter documents
based on specific criteria.
o Combine operators with logical operators ($and, $or, $not) to create more
complex queries.
Bash
// Find products with price greater than $800
db.products.find({ price: { $gt: 800 } })
// Find books published after 1800 (assuming "year" field exists)
db.books.find({ year: { $gt: 1800 } })
// Find products in stock and categorized as "Laptops"
db.products.find({ inStock: true, categories: "Laptops" })
6. Update Documents:
o Modify existing documents using the
db.<collection_name>.updateOne(<filter>, <update>) or
db.<collection_name>.updateMany(<filter>, <update>) methods.
o The $set operator allows updating specific fields within a document.
Bash
// Update a product's price in myDatabase1
db.products.updateOne({ name: "Laptop" }, { $set: { price: 849.99 }
})
// Update all books to set a default published year if missing
db.books.update
7. Update Documents
Bash
// Update all books to set a default published year if missing (using
upsert)
db.books.updateMany({ year: { $exists: false } }, { $set: { year: 2000 } },
{ upsert: true })
The upsert option with true creates a new document if no documents match the
filter.
8. Delete Documents:
Remove documents using the db.<collection_name>.deleteOne(<filter>) or
db.<collection_name>.deleteMany(<filter>) methods.
Bash
// Delete a product from myDatabase1
db.products.deleteOne({ name: "Laptop" })
// Delete all books with a specific title
db.books.deleteMany({ title: "Pride and Prejudice" })
9. Comparison Operators:
Explore additional comparison operators:
o $in: Check if a field's value is within a specified list.
o $nin: Check if a field's value is not within a list.
o $regex: Perform regular expression pattern matching.
Bash
// Find products with prices in the range $700-$900
db.products.find({ price: { $in: [700, 800, 900] } })
// Find books not titled "The Lord of the Rings"
db.books.find({ title: { $nin: ["The Lord of the Rings"] } })
// Find books with titles starting with "The" (case-insensitive)
db.books.find({ title: { $regex: /^The/i } })
10. Logical Operators:
Combine comparison operators using logical operators for more precise filtering:
o $and: Documents must satisfy all conditions within the array.
o $or: Documents can satisfy any condition within the array.
o $not: Inverts the match criteria.
Bash
// Find in-stock products with a price greater than $800 and categorized as
"Electronics"
db.products.find({ $and: [{ inStock: true }, { price: { $gt: 800 } }, {
categories: "Electronics" }] })
// Find books published after 1800 or titled "Pride and Prejudice"
db.books.find({ $or: [{ year: { $gt: 1800 } }, { title: "Pride and
Prejudice" }] })
// Find products not in stock or not categorized as "Laptops"
db.products.find({ $not: { $and: [{ inStock: true }, { categories:
"Laptops" }] } })
11. Indexes:
Create indexes on frequently used fields to improve query performance using
db.<collection_name>.createIndex({<field_name>: 1}).
Indexes allow faster retrieval of documents based on specific field values.
Bash
// Create an index on the "price" field in the "products" collection
db.products.createIndex({ price: 1 })
12. Collections:
Collections are logical groupings within a database that store similar documents.
Use different collections to organize data by category or purpose.
Create a new collection using db.createCollection("<collection_name>").
Bash
// Create a new collection for "customers" in myDatabase2
db.myDatabase2.createCollection("customers")
Remember:
Practice these operations throughout the TP to solidify your understanding.
Refer to the official MongoDB documentation (https://www.mongodb.com/docs/) for
more details on operators and functionalities.
By following these steps and exploring the concepts further, you'll gain a solid foundation for
working with MongoDB!