Objectives:: DB - Createcollection ("Products")
Objectives:: DB - Createcollection ("Products")
Prerequisites:
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)
Bash
Bash
Bash
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
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:
Bash
// Delete a product from myDatabase1
db.products.deleteOne({ name: "Laptop" })
9. Comparison Operators:
Bash
// Find products with prices in the range $700-$900
db.products.find({ price: { $in: [700, 800, 900] } })
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" }] })
11. Indexes:
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:
By following these steps and exploring the concepts further, you'll gain a solid foundation for
working with MongoDB!