Mongodb Programs
Mongodb Programs
Create Collection:
ProgBooksDB> db.createCollection("ProgrammingBooks")
Find Documents:
ProgBooksDB> db.ProgrammingBooks.find().pretty()
[
{
_id: ObjectId('664ee3b1924a8039f62202d8'),
title: 'The Pragmatic Programmer: Your Journey to Mastery',
author: 'David Thomas, Andrew Hunt',
category: 'Software Development',
year: 1999
},
{
_id: ObjectId('664ee452924a8039f62202d9'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202da'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202db'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Software Design',
year: 1994
},
{
_id: ObjectId('664ee452924a8039f62202dc'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein',
category: 'Algorithms',
year: 1990
},
{
_id: ObjectId('664ee452924a8039f62202dd'),
title: 'Python Crash Course: A Hands-On, Project-Based Introduction to
Programming',
author: 'Eric Matthes',
category: 'Python',
year: 2015
}
]
//verify the update operation by displaying books published before year 2010
ProgBooksDB> db.ProgrammingBooks.find({ year: { $lt: 2010 } }).pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e1'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Classic Programming Books',
year: 1994
},
{
_id: ObjectId('663eaaebae582498972202e2'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein',
category: 'Classic Programming Books',
year: 1990
},
{
_id: ObjectId('663eab05ae582498972202e4'),
title: 'The Pragmatic Programmer: Your Journey to Mastery',
author: 'David Thomas, Andrew Hunt',
category: 'Classic Programming Books',
year: 1999
}
]
MoviesDB> db.createCollection("Movies")
{ ok: 1 }
MoviesDB> db.Movies.insertMany([
{ title: "Inception", director: "Christopher Nolan", genre: "Science Fiction", year: 2010,
ratings: { imdb: 8.8, rottenTomatoes: 87 } },
{ title: "The Matrix", director: "Wachowskis", genre: "Science Fiction", year: 1999, ratings: {
imdb: 8.7, rottenTomatoes: 87 } },
{ title: "The Godfather", director: "Francis Ford Coppola", genre: "Crime", year: 1972,
ratings: { imdb: 9.2, rottenTomatoes: 97 } },
{ title: "Pulp Fiction", director: "Quentin Tarantino", genre: "Crime", year: 1994, ratings: {
imdb: 8.9, rottenTomatoes: 92 } },
{ title: "The Shawshank Redemption", director: "Frank Darabont", genre: "Drama", year:
1994, ratings: { imdb: 9.3, rottenTomatoes: 91 } },
{ title: "The Dark Knight", director: "Christopher Nolan", genre: "Action", year: 2008,
ratings: { imdb: 9.0, rottenTomatoes: 94 } },
{ title: "Fight Club", director: "David Fincher", genre: "Drama", year: 1999, ratings: { imdb:
8.8, rottenTomatoes: 79 } }
])
To select only the title and director fields from the Movies collection
companyDB> db.Employees.insertMany([
{ name: "Alice", age: 30, department: "HR", salary: 50000, joinDate: new Date("2015-01-15") },
{ name: "Bob", age: 24, department: "Engineering", salary: 70000, joinDate: new Date("2019-
03-10") },
{ name: "Charlie", age: 29, department: "Engineering", salary: 75000, joinDate: new
Date("2017-06-23") },
{ name: "David", age: 35, department: "Marketing", salary: 60000, joinDate: new Date("2014-
11-01") },
{ name: "Eve", age: 28, department: "Finance", salary: 80000, joinDate: new Date("2018-08-
19") }
])
1. $eq (Equal)
Geospatial Selectors:
geoDatabase> db.Places.insertMany([
{ name: "Central Park", location: { type: "Point", coordinates: [-73.9654, 40.7829] } },
{ name: "Times Square", location: { type: "Point", coordinates: [-73.9851, 40.7580] } },
{ name: "Brooklyn Bridge", location: { type: "Point", coordinates: [-73.9969, 40.7061] } },
{ name: "Empire State Building", location: { type: "Point", coordinates: [-73.9857, 40.7488]
} },
{ name: "Statue of Liberty", location: { type: "Point", coordinates: [-74.0445, 40.6892] } }
])
Geospatial Queries:
techDB> db.Devices.insertMany([
{ name: "Device A", status: 5 }, // Binary: 0101
{ name: "Device B", status: 3 }, // Binary: 0011
{ name: "Device C", status: 12 }, // Binary: 1100
{ name: "Device D", status: 10 }, // Binary: 1010
{ name: "Device E", status: 7 } // Binary: 0111
])
Bitwise Queries:
Example: Find the product named “Laptop” and project the review from the user “Alice”.
retailDB> db.Products.find(
{ name: "Laptop", "reviews.user": "Alice" },
{ "reviews.$": 1 }
).pretty()
2. The $elemMatch Projection Operator
Example: Find the product named “Laptop” and project the review where the rating is
greater than 4.
retailDB> db.Products.find(
{ name: "Laptop" },
{ reviews: { $elemMatch: { rating: { $gt: 4 } } } }
).pretty()
Example: Find the product named “Smartphone” and project the first review.
retailDB> db.Products.find(
{ name: "Smartphone" },
{ reviews: { $slice: 1 } }
).pretty()
5. Execute Aggregation operations ($avg, $min,$max, $push,
$addToSet etc.). students encourage to execute several queries to
demonstrate various aggregation operators)
1. $avg (Average)
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$product",
averagePrice: { $avg: "$price" }
}
} ]).pretty()
2. $min (Minimum)
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$product",
minPrice: { $min: "$price" }
}
} ]).pretty()
3. $max (Maximum)
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$product",
maxPrice: { $max: "$price" }
}
} ]).pretty()
Explanation:
create the listingsAndReviews collection and insert sample documents. Here are a few
example documents to illustrate the structure:
vacationRentals> db.listingsAndReviews.insertMany([
{
listing_url: "http://www.example.com/listing/123456",
name: "Beautiful Apartment",
address: {
street: "123 Main Street",
suburb: "Central",
city: "Metropolis",
country: "Wonderland"
},
host: {
name: "Alice",
picture_url: "http://www.example.com/images/host/host123.jpg"
} },
{
listing_url: "http://www.example.com/listing/654321",
name: "Cozy Cottage",
address: {
street: "456 Another St",
suburb: "North",
city: "Smallville",
country: "Wonderland"
},
host: {
name: "Bob",
picture_url: ""
} },
{
listing_url: "http://www.example.com/listing/789012",
name: "Modern Condo",
address: {
street: "789 Side Road",
suburb: "East",
city: "Gotham",
country: "Wonderland"
},
host: {
name: "Charlie",
picture_url: "http://www.example.com/images/host/host789.jpg"
}
} ])
db.listingsAndReviews.find(
{
"host.picture_url": { $exists: true, $ne: "" }
},
{
listing_url: 1,
name: 1,
address: 1,
"host.picture_url": 1
} ).pretty()
use MoviesDB
db.createCollection("Movies")
db.Movies.insertMany([
{ title: "Inception", director: "Christopher Nolan", genre: "Science Fiction", year: 2010,
ratings: { imdb: 8.8, rottenTomatoes: 87 } },
{ title: "The Matrix", director: "Wachowskis", genre: "Science Fiction", year: 1999, ratings: {
imdb: 8.7, rottenTomatoes: 87 } },
{ title: "The Godfather", director: "Francis Ford Coppola", genre: "Crime", year: 1972,
ratings: { imdb: 9.2, rottenTomatoes: 97 } },
{ title: "Pulp Fiction", director: "Quentin Tarantino", genre: "Crime", year: 1994, ratings: {
imdb: 8.9, rottenTomatoes: 92 } },
{ title: "The Shawshank Redemption", director: "Frank Darabont", genre: "Drama", year:
1994, ratings: { imdb: 9.3, rottenTomatoes: 91 } },
{ title: "The Dark Knight", director: "Christopher Nolan", genre: "Action", year: 2008,
ratings: { imdb: 9.0, rottenTomatoes: 94 } },
{ title: "Fight Club", director: "David Fincher", genre: "Drama", year: 1999, ratings: { imdb:
8.8, rottenTomatoes: 79 } }
])
// =====================
// 1. Creating Indexes
// =====================
db.Movies.updateOne(
db.Movies.updateOne(
{ title: "Inception" },
// Create the index on the actors field (automatically becomes a multikey index)
db.Movies.createIndex({ actors: 1 })
// =====================
// 2. Query Optimization
// =====================
// Run a query with an explain plan to see if the indexes are used
use CatalogDB
db.createCollection("CatalogData")
db.CatalogData.insertMany([
{ title: "Node.js Guide", description: "Learn server-side programming with Node.js and
JavaScript." },
{ title: "MongoDB Basics", description: "This book introduces MongoDB and NoSQL
database design." },
{ title: "Advanced Python", description: "Master advanced concepts in Python for data
science and web development." },
{ title: "Python Data Analysis", description: "Data analysis and visualization with Python and
Pandas." },
{ title: "Web Development", description: "Covers HTML, CSS, JavaScript, and modern
frameworks." }
])
// =========================================
// =========================================
// ==============================================
db.CatalogData.getIndexes()
// Step 1: Use the appropriate database
use CatalogDB
db.CatalogData.insertMany([
{ title: "Node.js Guide", description: "Learn server-side programming with Node.js and
JavaScript." },
{ title: "MongoDB Basics", description: "This book introduces MongoDB and NoSQL
database design." },
{ title: "Advanced Python", description: "Master advanced concepts in Python for data
science and web development." },
{ title: "Python Data Analysis", description: "Data analysis and visualization with Python and
Pandas." },
{ title: "Web Development", description: "Covers HTML, CSS, JavaScript, and modern
frameworks." }
])
db.CatalogData.aggregate([
$match: {
$text: {
}
},
$project: {
title: 1,
description: 1,
},
$sort: {
])