You are on page 1of 15

1.Explain in detail about CRUD operation in MongoDB.

CRUD operations describe the conventions of a user-interface that let users


view, search, and modify parts of the database.

MongoDB documents are modified by connecting to a server, querying the


proper documents, and then changing the setting properties before sending the
data back to the database to be updated. CRUD is data-oriented, and it’s
standardized according to HTTP action verbs.

When it comes to the individual CRUD operations:

● The Create operation is used to insert new documents in the MongoDB


database.
● The Read operation is used to query a document in the database.
● The Update operation is used to modify existing documents in the
database.
● The Delete operation is used to remove documents in the database.

How to Perform CRUD Operations

Now that we’ve defined MongoDB CRUD operations, we can take a look at
how to carry out the individual operations and manipulate documents in a
MongoDB database. Let’s go into the processes of creating, reading, updating,
and deleting documents, looking at each operation in turn.

Create Operations

For MongoDB CRUD, if the specified collection doesn’t exist,


the create operation will create the collection when it’s executed. Create
operations in MongoDB target a single collection, not multiple collections.
Insert operations in MongoDB are atomic on a single document level.

MongoDB provides two different create operations that you can use to insert
documents into a collection:

● db.collection.insertOne()
● db.collection.insertMany()

insertOne()
As the namesake, insertOne() allows you to insert one document into the
collection. For this example, we’re going to work with a collection called
RecordsDB. We can insert a single entry into our collection by calling the
insertOne() method on RecordsDB. We then provide the information we want to
insert in the form of key-value pairs, establishing the schema.

db.RecordsDB.insertOne({
name: "Bruno",
age: "5 years",
species: "Dog",
ownerAddress: "Kullu, Himachal Pradesh",
chipped: true
})

If the create operation is successful, a new document is created. The function


will return an object where “acknowledged” is “true” and “insertID” is the
newly created “ObjectId.”

> db.RecordsDB.insertOne({
... name: "Bruno",
... age: "5 years",
... species: "Dog",
... ownerAddress: "Kullu, Himachal Pradesh",
... chipped: true
... })
{
"acknowledged" : true,
"insertedId" :
ObjectId("8665c57d5e6b9ceb866b9ceb")
}

insertMany()
It’s possible to insert multiple items at one time by calling
the insertMany() method on the desired collection. In this case, we pass multiple
items into our chosen collection (RecordsDB) and separate them by commas.
Within the parentheses, we use brackets to indicate that we are passing in a list
of multiple entries. This is commonly referred to as a nested method.

db.RecordsDB.insertMany([{
name: "Bruno",
age: "5 years",
species: "Dog",
ownerAddress: "Kullu, Himachal Pradesh",
chipped: true},
{name: "Mitthu",
age: "3 years",
species: "Parrot",
ownerAddress: "Kullu, Himachal Pradesh",
chipped: true}])

db.RecordsDB.insertMany([{ name: "Bruno", age: "5 years",


species: "Dog",
ownerAddress: "Kullu, Himachal Pradesh", chipped: true},
{name: "Mitthu", age: "3 years",
species: "Parrot", ownerAddress: "Kullu, Himachal
Pradesh", chipped: true}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5fd98ea9ce6e8850d88270b4"),
ObjectId("5fd98ea9ce6e8850d88270b5")
]
}
2.What is a namespace in MongoDB? 
A namespace is a canonical name for a collection or index in MongoDB. The namespace is basically a
combination of the database name and the name of the collection or index,

like so: [database-name]. [collection-or-index-name] .

3.How do I handle 404 responses? 


All you need to do is add a middleware function at the very bottom of the stack (below all other
functions) to

handle a 404 response: app. use((req, res, next) => { res. status(404).

4.Connect to a running mongo instance, use a database named mongo_practice.

Document all your queries

Insert the documents into a movies collection.

query the movies collection to
1. get all documents

2. get all documents with writer set to "Quentin Tarantino"

3. get all documents where actors include "Brad Pitt"

4. get all documents with franchise set to "The Hobbit"

5. get all movies released in the 90s

6. get all movies released before the year 2000 or after 2010

MongoDB Practice

MongoDB Exercise in mongo shell

create database

Connect to a running mongo instance, use a database named mongo_practice.


use mongo_practice
Insert Documents

Insert the following documents into a movies collection.

title : Fight Club

writer : Chuck Palahniuk

year : 1999

actors : [

Brad Pitt

Edward Norton

db.movies.insert({title:"Fight Club", writer: "Chuck Palahniuk", year: "1999",


actors:["Brad Pitt", "Edward Norton"]})

title : Pulp Fiction

writer : Quentin Tarantino

year : 1994

actors : [

John Travolta

Uma Thurman

db.movies.insert({title:"Pulp Fiction", writer:"Quentin Tarantino", year:"2009",


actors:["John Travolta", "Uma Thurman"]})

title : Inglorious Basterds

writer : Quentin Tarantino

year : 2009
actors : [

Brad Pitt

Diane Kruger

Eli Roth

db.movies.insert({title:"Inglorious Basterds", writer:"Quentin Tarantino",


year:"2009", actors:["Brad Pitt", "Diane Kruger", "Eli Roth"]})

title : The Hobbit: An Unexpected Journey

writer : J.R.R. Tolkein

year : 2012

franchise : The Hobbit

db.movies.insert({title:"The Hobbit: An unexpected Journey", writer:"J.R.R.


Tolkein", year:"2012",franchise:"The Hobbit"})

title : The Hobbit: The Desolation of Smaug

writer : J.R.R. Tolkein

year : 2013

franchise : The Hobbit

db.movies.insert({title:"The Hobbit: The Desolation of Smaug", writer:"J.R.R


Tolkien", year:"2013", franchise:"The Hobbit"})

title : The Hobbit: The Battle of the Five Armies

writer : J.R.R. Tolkein

year : 2012

franchise : The Hobbit


synopsis : Bilbo and Company are forced to engage in a war against an array of
combatants and keep the Lonely Mountain from falling into the hands of a
rising darkness.

db.movies.insert({title:"The Hobbit: The Battle of the Five Armies",


writer:"J.R.R Tolkien", year:"2002", franchise:"The Hobbit", synopsis:"Bilbo and
Company are forced to engage in a war against an array of combatants and
keep the Lonely Mountain from falling into the hands of a rising darkness."})

title : Pee Wee Herman's Big Adventure

db.movies.insert({title:"Pee Wee Herman's Big Adventures"})

title : Avatar

db.movies.insert({title:"Avatar"})

Query / Find Documents

query the movies collection to

get all documents

db.movies.find()

get all documents with writer set to "Quentin Tarantino"

db.movies.find({writer:"Quentin Tarantino"})

get all documents where actors include "Brad Pitt"

db.movies.find({actors:"Brad Pitt"})

get all documents with franchise set to "The Hobbit"

db.movies.find({franchise:"The Hobbit"})

get all movies released in the 90s

db.movies.find({year:{$gt:"1990", $lt:"2000"}})
get all movies released before the year 2000 or after 2010

db.movies.find({$or:[{year:{$gt:"2010"}},{year: {$lt:"2000"}}]})

Update Documents

add a synopsis to "The Hobbit: An Unexpected Journey" : "A reluctant hobbit,


Bilbo Baggins, sets out to the Lonely Mountain with a spirited group of
dwarves to reclaim their mountain home - and the gold within it - from the
dragon Smaug."

db.movies.update({_id:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a5")}, {$set:
{synopsis:"A reluctant hobbit, Bilbo Baggins, sets out to the Lonely Mountain
with a spirited group of dwarves to reclaim their mountain home - and the gold
within it - from the dragon Smaug."}})

add a synopsis to "The Hobbit: The Desolation of Smaug" : "The dwarves, along
with Bilbo Baggins and Gandalf the Grey, continue their quest to reclaim
Erebor, their homeland, from Smaug. Bilbo Baggins is in possession of a
mysterious and magical ring."

db.movies.update({_id:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a6")}, {$set:
{synopsis:"The dwarves, along with Bilbo Baggins and Gandalf the Grey,
continue their quest to reclaim Erebor, their homeland, from Smaug. Bilbo
Baggins is in possession of a mysterious and magical ring."}})

add an actor named "Samuel L. Jackson" to the movie "Pulp Fiction"

db.movies.update({_id:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a5")}, {$push:
{actors:"Samuel L. Jackson"}})

Text Search

find all movies that have a synopsis that contains the word "Bilbo"

db.movies.find({synopsis:{$regex:"Bilbo"}})

find all movies that have a synopsis that contains the word "Gandalf"

db.movies.find({synopsis:{$regex:"Gandalf"}})
find all movies that have a synopsis that contains the word "Bilbo" and not the
word "Gandalf"

db.movies.find({$and:[{synopsis:{$regex:"Bilbo"}},
{synopsis:{$not:/Gandalf/}}]})

find all movies that have a synopsis that contains the word "dwarves" or
"hobbit"

db.movies.find({$or:[{synopsis:{$regex:"dwarves"}}, {synopsis:
{$regex:"hobbit"}}]})

find all movies that have a synopsis that contains the word "gold" and
"dragon"

db.movies.find({$and:[{synopsis:{$regex:"gold"}}, {synopsis:
{$regex:"dragon"}}]})

Delete Documents

delete the movie "Pee Wee Herman's Big Adventure"

db.movies.remove({_id:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a4")})

delete the movie "Avatar"

db.movies.remove({_id:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a5")})

Relationships

Insert the following documents into a users collection

username : GoodGuyGreg

first_name : "Good Guy"

last_name : "Greg"

db.users.insert({_id:1,username:"GoodGuyGreg", first_name:"Good Guy",


last_name:"Greg"})

username : ScumbagSteve

full_name :
first : "Scumbag"

last : "Steve"

db.users.insert({_id:2, username:"ScumbagSteve", fullname:{first: "Scumbag",


last:"Steve"}})

Insert the following documents into a posts collection

username : GoodGuyGreg

title : Passes out at party

body : Wakes up early and cleans house

db.posts.insert({username:"GoodGuyGreg", title:"Passes out at Party",


body:"Raises your credit score"})

username : GoodGuyGreg

title : Steals your identity

body : Raises your credit score

db.posts.insert({ username:"GoodGuyGreg", title:"Steals your identity",


body:"Raises your credit score"})

username : GoodGuyGreg

title : Reports a bug in your code

body : Sends you a Pull Request

db.posts.insert({username:"GoodGuyGreg", title:"Reports a bug in your code",


body:"Sends you a pull request"})

username : ScumbagSteve

title : Borrows something

body : Sells it
db.posts.insert({ username:"ScumbagSteve", title:"Borrows something",
body:"Sells it"})

username : ScumbagSteve

title : Borrows everything

body : The end

db.posts.insert({ username:"ScumbagSteve", title:"Borrows everything",


body:"The end"})

username : ScumbagSteve

title : Forks your repo on github

body : Sets to private

db.posts.insert({username:"ScumbagSteve", title:"Forks your repo on github",


body:"Sets to private"})

Insert the following documents into a comments collection

username : GoodGuyGreg

comment : Hope you got a good deal!

post : [post_obj_id]

where [post_obj_id] is the ObjectId of the posts document: "Borrows


something"

db.comments.insert({ username:"GoodGuyGreg", comment:"Hope you got a


good deal!", post:ObjectId("5ca0b7e96435f98b5901f463")})

username : GoodGuyGreg

comment : What's mine is yours!

post : [post_obj_id]
where [post_obj_id] is the ObjectId of the posts document: "Borrows
everything"

db.comments.insert({username:"GoodGuyGreg", comment:"What's mine is


yours!", post:ObjectId("5ca0b9706435f98b5901f46a")})

username : GoodGuyGreg

comment : Don't violate the licensing agreement!

post : [post_obj_id]

where [post_obj_id] is the ObjectId of the posts document: "Forks your repo
on github

db.comments.insert({username:"GoodGuyGreg", comment:"Don't violate the


licensing agreement!", post:ObjectId("6c6d8e9f3c5a2c89d8e6d9c1a6")})

username : ScumbagSteve

comment : It still isn't clean

post : [post_obj_id]

where [post_obj_id] is the ObjectId of the posts document: "Passes out at


party"

db.comments.insert({username:"ScumbagSteve", comment:"It still isn't clean",


post:ObjectId("6c6d8e9f3c5a2c89d7a8c1c3d4a6e")})

username : ScumbagSteve

comment : Denied your PR cause I found a hack

post : [post_obj_id]

where [post_obj_id] is the ObjectId of the posts document: "Reports a bug in


your code"
db.comments.insert({username:"ScumbagSteve", comment:"Denied your PR
cause I found a hack", post:ObjectId("6c6d8e9f3c5a2c89d7a8c1c3d4a6f")})

Querying related collections

find all users

db.users.find().pretty()

find all posts

db.posts.find().pretty()

find all posts that was authored by "GoodGuyGreg"

db.posts.find({username:"GoodGuyGreg"})

find all posts that was authored by "ScumbagSteve"

db.posts.find({username:"ScumbagSteve"})

find all comments

db.comments.find().pretty()

find all comments that was authored by "GoodGuyGreg"

db.comments.find({username:"GoodGuyGreg"})

find all comments that was authored by "ScumbagSteve"

db.comments.find({username:"ScumbagSteve"})

find all comments belonging to the post "Reports a bug in your code"

Import a csv to mongodb

{ "_id" : "02906", "city" : "PROVIDENCE", "pop" : 31069, "state" : "RI",


"capital" : { "name" : "Providence", "electoralCollege" : 4 } }

{ "_id" : "02108", "city" : "BOSTON", "pop" : 3697, "state" : "MA", "capital" :


{ "name" : "Boston", "electoralCollege" : 11 } }
{ "_id" : "10001", "city" : "NEW YORK", "pop" : 18913, "state" : "NY", "capital" :
{ "name" : "Albany", "electoralCollege" : 29 } }

{ "_id" : "01012", "city" : "CHESTERFIELD", "pop" : 177, "state" : "MA", "capital"


: { "name" : "Boston", "electoralCollege" : 11 } }

{ "_id" : "32801", "city" : "ORLANDO", "pop" : 9275, "state" : "FL", "capital" :


{ "name" : "Tallahassee", "electoralCollege" : 29 } }

{ "_id" : "12966", "city" : "BANGOR", "pop" : 2867, "state" : "NY", "capital" :


{ "name" : "Albany", "electoralCollege" : 29 } }

{ "_id" : "32920", "city" : "CAPE CANAVERAL", "pop" : 7655, "state" : "FL",


"capital" : { "name" : "Tallahassee", "electoralCollege" : 29 } }

{ "_id" : "NY", "name" : "New York", "pop" : 28300000, "state" : 1788 }

{ "_id" : "33125", "city" : "MIAMI", "pop" : 47761, "state" : "FL", "capital" :


{ "name" : "Tallahassee", "electoralCollege" : 29 } }

{ "_id" : "RI", "name" : "Rhode Island", "pop" : 1060000, "state" : 1790 }

{ "_id" : "MA", "name" : "Massachusetts", "pop" : 6868000, "state" : 1790 }

{ "_id" : "FL", "name" : "Florida", "pop" : 6800000, "state" : 1845 }

{ "_id" : "1", "name" : "Tom", "addresses" : [ "01001", "12997" ] }

{ "_id" : "02907", "city" : "CRANSTON", "pop" : 25668, "state" : "RI", "capital" : {


"name" : "Providence", "electoralCollege" : 4 } }

{ "_id" : "2", "name" : "Bill", "addresses" : [ "01001", "12967", "32920" ] }

{ "_id" : "3", "name" : "Mary", "addresses" : [ "32801", "32920", "33125" ] }

{ "_id" : "12967", "city" : "NORTH LAWRENCE", "pop" : 943, "state" : "NY",


"capital" : { "name" : "Albany", "electoralCollege" : 29 } }

{ "_id" : "01001", "city" : "AGAWAM", "pop" : 15338, "state" : "MA", "capital" :


{ "name" : "Boston", "electoralCollege" : 11 } }

{ "_id" : "12997", "city" : "WILMINGTON", "pop" : 958, "state" : "NY", "capital" :


{ "name" : "Albany", "electoralCollege" : 29 } }
mongoimport --db <database_name> --collection <collection_name> --file

Show name and population of the cities where the population is over 10000

db.docs.find({city:{$exists:true}}, {_id:0, city:1, pop:1},{ pop:{$gt:10000}})

Show the name and population of the state based on the cities shown

db.docs.aggregate([{$match:{city:{$exists: true}}},{$group:{_id:"$state", "Total


Pop": {$sum:"$pop"}}}])

Show the total cities in NY as 'Population'

db.docs.aggregate([{$match:{state:"NY"}},{$group:{_id:"$state", "Total Pop":


{$sum:"$pop"}}}])

Show the _id, city, name of the capital city of each state with a popultaion
greater than 20,000.

db.docs.find({city:{$exists:true}, pop:{$gt:20000}}, {city:1, "capital.name":1})

You might also like