MongoDB - 2
MongoDB - 2
• Question 1
• Question 3
• Question 4
• Projection operators
• Question 5
• Aggregation operations
• Question 6
• Question 7
MongoDB Operations
If you want to use a specific database, switch to that database using the use command. If the
database doesn’t exist, MongoDB will create it implicitly when you insert data into it:
switched to db ProgBooksDB
ProgBooksDB>
To create the ProgrammingBooks collection, use the createCollection() method. This step is
optional because MongoDB will automatically create the collection when you insert data into it,
but you can explicitly create it if needed:
ProgBooksDB> db.createCollection("ProgrammingBooks")
Insert operations
Use the insertOne() method to insert a new document into the ProgrammingBooks collection:
ProgBooksDB> db.ProgrammingBooks.insertOne({
year: 1999
})
ProgBooksDB> db.ProgrammingBooks.insertMany([
{
title: "Clean Code: A Handbook of Agile Software Craftsmanship",
year: 2008
},
category: "JavaScript",
year: 2008
},
{
title: "Design Patterns: Elements of Reusable Object-Oriented Software",
year: 1994
},
category: "Algorithms",
year: 1990
},
])
Query operations
1) Find All Documents
ProgBooksDB> db.ProgrammingBooks.find().pretty()
3) Update Operations
ProgBooksDB>db.ProgrammingBooks.updateOne(
To update multiple books (e.g., update the category of books published before 2010):
ProgBooksDB> db.ProgrammingBooks.updateMany(
//verify the update operation by displaying books published before year 2010
ProgBooksDB> db.ProgrammingBooks.find({ year: { $lt: 2010 } }).pretty()
4) Delete Operations
To delete a specific book from the collection (e.g., delete a book by title):
To delete multiple books based on a condition (e.g., delete all books published before 1995):
ProgBooksDB> db.ProgrammingBooks.deleteMany({ year: { $lt: 1995 } })
You can check whether the specified documents were deleted by displaying the contents of the
collection.
ProgBooksDB> db.ProgrammingBooks.deleteMany({})
ProgBooksDB> db.ProgrammingBooks.find().pretty()
Projection Operations
In MongoDB, a projection refers to the mechanism of specifying which fields (or columns)
should be returned from a query result. When querying a collection, you can use projection to
control the shape of the returned documents by specifying which fields to include or exclude.
In MongoDB, projection is typically specified as the second parameter to the find() method. The
projection parameter takes an object where keys represent the fields to include or exclude, with
values of 1 (include) or 0 (exclude).
In MongoDB, the equivalent of SQL’s WHERE clause is achieved using query filters within
the find() method. You can also combine multiple conditions using logical operators
like $and and $or. Here’s how you can illustrate the usage of these features:
First, let’s assume we have a collection named ProgrammingBooks with the following
documents:
• title: "Clean Code", author: "Robert C. Martin", category: "Software Development", year:
2008
• title: "JavaScript: The Good Parts", author: "Douglas Crockford", category: "JavaScript",
year: 2008
• title: "Design Patterns", author: "Erich Gamma", category: "Software Design", year: 1994
• title: "Introduction to Algorithms", author: "Thomas H. Cormen", category:
"Algorithms", year: 2009
• title: "Python Crash Course", author: "Eric Matthes", category: "Python", year: 2015
switched to db newDB
newDB> db.createCollection("ProgrammingBooks")
{ ok: 1 }
newDB> db.ProgrammingBooks.insertMany([
{ title: "Clean Code", author: "Robert C. Martin", category: "Software Development", year:
2008 },
{ title: "JavaScript: The Good Parts", author: "Douglas Crockford", category: "JavaScript",
year: 2008 },
{ title: "Design Patterns", author: "Erich Gamma", category: "Software Design", year: 1994 },
{ title: "Python Crash Course", author: "Eric Matthes", category: "Python", year: 2015 }
]);
To query documents with specific conditions, you can use the find() method with a filter object.
For example, to find books published in the year 2008:
The $and operator is used to combine multiple conditions that must all be true. Here’s how to
find books that are in the “Software Development” category and published in the year 2008:
newDB>db.ProgrammingBooks.find({
$and: [
{ year: 2008 }
}).pretty()
In this query:
• Both conditions must be met for a document to be included in the result.
The $or operator is used to combine multiple conditions where at least one must be true. Here’s
how to find books that are either in the “JavaScript” category or published in the year 2015:
newDB> db.ProgrammingBooks.find({
$or: [
{ category: "JavaScript" },
{ year: 2015 }
]
}).pretty()
In this query:
You can combine $and and $or operators for more complex queries. For example, to find books
that are either in the “Software Development” category and published after 2007, or in the
“Python” category:
newDB> db.ProgrammingBooks.find({
$or: [
$and: [
{ category: "Software Development" },
},
{ category: "Python" }
}).pretty()
In this query:
• The document will be included if it meets the combined $and conditions of being in the
“Software Development” category and published after 2007, or if it is in the “Python”
category.
Question 2
Develop a MongoDB query to select certain fields and ignore some fields of the documents
from any collection.
To select certain fields and ignore others in MongoDB, you use projections in your queries.
Projections allow you to specify which fields to include or exclude in the returned documents.
MoviesDB> db.createCollection("Movies")
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 } }
]);
When using the find() method, the first parameter is the query filter, and the second parameter is
the projection object. The projection object specifies the fields to include (using 1) or exclude
(using 0).
Including Specific Fields
To select only the title and director fields from the Movies collection:
In this query:
In this query:
You can also combine a query filter with a projection. For example, to find movies directed by
“Christopher Nolan” and include only the title and year fields:
In this query:
• The filter { director: "Christopher Nolan" } selects documents where the director is
“Christopher Nolan”.
• The projection { title: 1, year: 1, _id: 0 } includes only the title and year fields and
excludes the _id field.
In MongoDB, projections are used to control which fields are included or excluded in the
returned documents. This is useful for optimizing queries and reducing the amount of data
transferred over the network. You specify projections as the second parameter in
the find() method.
Example Scenario
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 } }
]);
Suppose you want to display the first 5 documents from the Movies collection, including only
the title, director, and year fields. Here’s how you can do it:
Explanation:
• { title: 1, director: 1, year: 1, _id: 0 }: This projection includes the title, director,
and year fields, and excludes the _id field.
• .limit(5): This method limits the query result to the first 5 documents.
By using the find() method with a projection and the limit() method, you can efficiently query
and display a subset of documents from a MongoDB collection. This approach helps manage
large datasets by retrieving only a specific number of documents, which is particularly useful for
paginating results in applications.
Question 3
Execute query selectors (comparison selectors, logical selectors ) and list out the results on
any collection
Let’s create a new collection called Employees and insert some documents into it. Then, we’ll
demonstrate the use of comparison selectors and logical selectors to query this collection.
First, we need to create the Employees collection and insert some sample documents.
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)
Find employees who are in the “Engineering” department and have a salary greater than 70000.
companyDB> db.Employees.find({
$and: [
{ department: "Engineering" },
}).pretty()
Find employees who are either in the “HR” department or have a salary less than 60000.
companyDB> db.Employees.find({
$or: [
{ department: "HR" },
{ salary: { $lt: 60000 } }
]
}).pretty()
department: {
}).pretty()
Find employees who are neither in the “HR” department nor have a salary greater than 75000.
companyDB> db.Employees.find({
$nor: [
{ department: "HR" },
}).pretty()
Execute query selectors (Geospatial selectors, Bitwise selectors ) and list out the results on
any collection
Let’s extend our MongoDB examples to include queries using geospatial selectors and bitwise
selectors. We will create a new collection called Places for geospatial queries and a collection
called Devices for bitwise queries.
Geospatial Selectors
geoDatabase> db.Places.insertMany([
{ name: "Central Park", location: { type: "Point", coordinates: [-73.9654, 40.7829] } },
{ name: "Empire State Building", location: { type: "Point", coordinates: [-73.9857, 40.7488] }
},
])
// Create a geospatial index
Find places near a specific coordinate, for example, near Times Square.
geoDatabase> db.Places.find({
location: {
$near: {
$geometry: {
type: "Point",
},
}
}
}).pretty()
Find places within a specific polygon, for example, an area covering part of Manhattan.
geoDatabase> db.Places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[-70.016, 35.715],
[-74.014, 40.717],
[-73.990, 40.730],
[-73.990, 40.715],
[-70.016, 35.715]
]
}
}).pretty()
Bitwise Selectors
techDB> db.Devices.insertMany([
])
techDB> db.Devices.find({
status: { $bitsAllSet: [0, 2] }
}).pretty()
2. $bitsAnySet (Find documents where any of the bits are set)
Find devices where the binary status has at least the 2nd bit set (binary mask 0010, or decimal 2).
techDB> db.Devices.find({
}).pretty()
3. $bitsAllClear (Find documents where all bits are clear)
Find devices where the binary status has both the 2nd and 4th bits clear (binary mask 1010, or
decimal 10).
techDB> db.Devices.find({
}).pretty()
Find devices where the binary status has at least the 1st bit clear (binary mask 0001, or decimal
1).
techDB> db.Devices.find({
}).pretty()
Question 4
Projection Operators
Create and demonstrate how projection operators (,elematch and $slice) would be used in
the MondoDB.
To demonstrate the use of projection operators ($, $elemMatch, and $slice) in MongoDB, let’s
create a Products collection. We’ll insert documents that include arrays, which will allow us to
showcase these operators effectively.
switched to db retailDB
retailDB> db.Products.insertMany([
{
name: "Laptop",
brand: "BrandA",
features: [
reviews: [
},
{
name: "Smartphone",
brand: "BrandB",
features: [
],
reviews: [
])
Use Projection Operators
The $ operator is used to project the first matching element from an array of embedded
documents.
Example: Find the product named “Laptop” and project the review from the user “Alice”.
retailDB> db.Products.find(
{ "reviews.$": 1 }
).pretty()
2. The $elemMatch Projection Operator
The $elemMatch operator is used to project the first matching element from an array based on
specified criteria.
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()
retailDB> db.Products.find(
{ name: "Smartphone" },
{ reviews: { $slice: 1 } }
).pretty()
Example: Find the product named “Laptop” and project the name, the first two features, and the
review with the highest rating.
retailDB> db.Products.find(
{ name: "Laptop" },
{
name: 1,
features: { $slice: 2 },
).pretty()
Using projection operators in MongoDB, you can fine-tune the data returned by your queries:
• The $ operator is useful for projecting the first matching element from an array.
• The $elemMatch operator allows you to project the first array element that matches
specified criteria.
• The $slice operator lets you project a subset of an array, such as the first n elements or a
specific range.
Question 5
Aggregation operations
To demonstrate aggregation operations such as $avg, $min, $max, $push, and $addToSet in
MongoDB, we will use a Sales collection. This collection will contain documents representing
sales transactions.
First, we’ll create the Sales collection and insert sample documents.
salesDB> db.Sales.insertMany([
{ date: new Date("2024-01-01"), product: "Laptop", price: 1200, quantity: 1, customer: "Amar"
},
{ date: new Date("2024-01-02"), product: "Laptop", price: 1200, quantity: 2, customer: "Babu"
},
{ date: new Date("2024-01-03"), product: "Mouse", price: 25, quantity: 5, customer: "Chandra"
},
{ date: new Date("2024-01-04"), product: "Keyboard", price: 45, quantity: 3, customer: "Amar"
},
{ date: new Date("2024-01-05"), product: "Monitor", price: 300, quantity: 1, customer: "Babu"
},
{ date: new Date("2024-01-06"), product: "Laptop", price: 1200, quantity: 1, customer: "Deva"
}
])
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$product",
}
}
2. $min (Minimum)
salesDB> db.Sales.aggregate([
$group: {
_id: "$product",
]).pretty()
3. $max (Maximum)
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$product",
]).pretty()
$group: {
_id: "$customer",
products: { $push: "$product" }
]).pretty()
Group sales by customer and add each unique purchased product to an array.
salesDB> db.Sales.aggregate([
{
$group: {
_id: "$customer",
]).pretty()
Example: Calculate the total quantity and total sales amount for each product, and list all
customers who purchased each product.
salesDB> db.Sales.aggregate([
$group: {
_id: "$product",
}
]).pretty()
By using aggregation operations such as $avg, $min, $max, $push, and $addToSet, you can
perform complex data analysis and transformations on MongoDB collections. These operations
enable you to calculate averages, find minimum and maximum values, push values into arrays,
and create sets of unique values. The examples provided show how to use these operators to
analyze a Sales collection.
Question 6
use restaurantDB
db.restaurants.insertMany([
location: "Jayanagar",
reviews: [
},
{
name: "Burger Joint",
cuisine: "American",
location: "Koramangala",
reviews: [
},
{
name: "Pasta House",
cuisine: "Italian",
location: "Rajajinagar",
reviews: [
},
{
cuisine: "Indian",
location: "Jayanagar",
reviews: [
},
cuisine: "Mexican",
location: "Jayanagar",
reviews: [
{ user: "Ishaan", rating: 5, comment: "Fantastic tacos!" },
{ user: "Jaya", rating: 4, comment: "Very authentic" }
])
db.restaurants.aggregate([
$match: {
location: "Jayanagar"
},
{
$unwind: "$reviews"
},
$group: {
_id: "$name",
},
$sort: {
averageRating: -1
}
},
{
$project: {
_id: 0,
restaurant: "$_id",
averageRating: 1,
totalReviews: 1
},
$skip: 1
]).pretty()
Now, let’s execute an aggregation pipeline that includes
the $match, $unwind, $group, $sort, $project, and $skip stages.
Aggregation Pipeline Explanation
2. $unwind: Deconstruct the reviews array from each document to output a document for
each review.
3. $group: Group the documents by restaurant name and calculate the average rating and
total number of reviews.
5. $project: Restructure the output to include only the restaurant name, average rating, and
total reviews.
Find all listings with listing_url, name, address, host_picture_url in the listings And
Reviews collection that have a host with a picture url
First, switch to or create the database you want to use. For this example, let’s call the
database vacationRentals.
test> use vacationRentals
switched to db vacationRentals
vacationRentals>
listing_url: "http://www.example.com/listing/123456",
address: {
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: {
suburb: "North",
city: "Smallville",
country: "Wonderland"
},
host: {
name: "Bob",
picture_url: ""
},
listing_url: "http://www.example.com/listing/789012",
suburb: "East",
city: "Gotham",
country: "Wonderland"
},
host: {
name: "Charlie",
picture_url: "http://www.example.com/images/host/host789.jpg"
])
Query to Find Listings with Host Picture URLs
Now that the collection is set up, you can run the query to find all listings
with listing_url, name, address, and host_picture_url where the host has a picture URL.
db.listingsAndReviews.find(
{
"host.picture_url": { $exists: true, $ne: "" }
},
listing_url: 1,
name: 1,
address: 1,
"host.picture_url": 1
).pretty()
Explanation:
• Query Filter:
• "host.picture_url": { $exists: true, $ne: "" }: This part of the query ensures that
only documents where the host.picture_url field exists and is not an empty string
are selected.
• Projection:
use ecommerce
db.products.insertMany([
{
product_id: 1,
name: "Laptop",
category: "Electronics",
price: 1200,
reviews: [
},
product_id: 2,
name: "Smartphone",
category: "Electronics",
price: 800,
reviews: [
{ user: "Dave", rating: 4, comment: "Good phone" },
]
},
product_id: 3,
name: "Headphones",
category: "Accessories",
price: 150,
reviews: [
])
db.products.aggregate([
{
$unwind: "$reviews"
},
$group: {
_id: "$name",
totalReviews: { $sum: 1 },
averageRating: { $avg: "$reviews.rating" },
comments: { $push: "$reviews.comment" }
},
{
$project: {
_id: 0,
product: "$_id",
totalReviews: 1,
averageRating: 1,
comments: 1
}
]).pretty()
This script will set up the ecommerce database, populate the products collection with sample
data, and execute an aggregation query to summarize the reviews.
Explanation:
1. $unwind: Deconstructs the reviews array from each document to output a document for
each element.
3. $project: Restructures the output documents to include the product name, total reviews,
average rating, and comments.