0% found this document useful (0 votes)
7 views

Lab6 1

Uploaded by

sgdenimhouse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lab6 1

Uploaded by

sgdenimhouse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab 6

NoSQL Database: Document Store using MongoDB

I. Objectives

➢ Performing CRUD operations using MongoDB


➢ Exploring Mongo Shell.

Overview:

❖ Syntax of CRUD Operations:

insert(document or array of documents)

insertOne( 'document', { writeConcern: 'document' } )

insertMany( { [ document 1 , document 2, ... ] }, { writeConcern: document, ordered: boolean } )

find(query, projection)

findOne(query, projection)

update(query, update)

updateOne( query, update, { upsert: boolean, writeConcern: document } )

updateMany( query, update, { upsert: boolean, writeConcern: document } )

replaceOne( query, replacement, { upsert: boolean, writeConcern: document } )

remove(query, justOne)

findAndModify(query, sort, update, options[optional])

❖ Create

db.people.insert({name: 'Tom', age: 28});

Or

db.people.save({name: 'Tom', age: 28});

The difference with save is that if the passed document contains an _id field, if a document already

exists with that _id it will be updated instead of being added as new.

Two new methods to insert documents into a collection, in MongoDB:

- Use insertOne to insert only one record:

db.people.insertOne({name: 'Tom', age: 28});

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB
- Use insertMany to insert multiple records:

db.people.insertMany([{name: 'Tom', age: 28},{name: 'John', age: 25}, {name: 'Kathy', age: 23}])

❖ Update

Update the entire object:

db.people.update({name: 'Tom'}, {age: 29, name: 'Tom'})

db.people.updateOne({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace only first matching
document.

db.people.updateMany({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace all matching

documents.

Or just update a single field of a document. In this case age:

db.people.update({name: 'Tom'}, {$set: {age: 29}})

You can also update multiple documents simultaneously by adding a third parameter. This query

will update all documents where the name equals Tom:

db.people.update({name: 'Tom'}, {$set: {age: 29}}, {multi: true})

db.people.updateOne({name: 'Tom'},{$set:{age: 30}) //Will update only first matching document.

db.people.updateMany({name: 'Tom'},{$set:{age: 30}}) //Will update all matching documents.

If a new field is coming for update, that field will be added to the document.

db.people.updateMany({name: 'Tom'},{$set:{age: 30, salary:50000}})// Document will have

`salary` field as well.

If a document is needed to be replaced,

db.collection.replaceOne({name:'Tom'}, {name:'Lakmal',age:25,address:'Sri Lanka'})

can be used.

Note: Fields you use to identify the object will be saved in the updated document. Field that are

not defined in the update section will be removed from the document.

❖ Delete

Deletes all documents matching the query parameter:

db.people.deleteMany({name: 'Tom'})

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB
db.people.remove({name: 'Tom'})

Or just one

db.people.deleteOne({name: 'Tom'})

db.people.remove({name: 'Tom'}, true)

MongoDB's remove() method. If you execute this command without any argument or without empty

argument it will remove all documents from the collection.

db.people.remove();

or

db.people.remove({});

❖ Read

Query for all the docs in the people collection that have a name field with a value of 'Tom':

db.people.find({name: 'Tom'})

Or just the first one:

db.people.findOne({name: 'Tom'})

You can also specify which fields to return by passing a field selection parameter. The following

will exclude the _id field and only include the age field:

db.people.find({name: 'Tom'}, {_id: 0, age: 1})

Note: by default, the _id field will be returned, even if you don't ask for it. If you would like not to

get the _id back, you can just follow the previous example and ask for the _id to be excluded by

specifying _id: 0 (or _id: false).

If you want to find sub record like address object contains country, city, etc.

db.people.find({'address.country': 'US'})

& specify field too if required

db.people.find({'address.country': 'US'}, {'name': true, 'address.city': true})

Remember that the result has a `.pretty()` method that pretty-prints resulting JSON:

db.people.find().pretty()

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB
❖ More update operators

You can use other operators besides $set when updating a document.

The $push operator allows you to push a value into an array, in this case we will add a new nickname to
the nicknames array.

db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}})

// This adds the string 'Tommy' into the nicknames array in Tom's document.

The $pull operator is the opposite of $push, you can pull specific items from arrays.

db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}})

// This removes the string 'Tommy' from the nicknames array in Tom's document.

The $pop operator allows you to remove the first or the last value from an array.

Let's say Tom's document has a property called siblings that has the value ['Marie', 'Bob', 'Kevin', 'Alex'].

db.people.update({name: 'Tom'}, {$pop: {siblings: -1}})

// This will remove the first value from the siblings array, which is 'Marie' in this case.

db.people.update({name: 'Tom'}, {$pop: {siblings: 1}})

// This will remove the last value from the siblings array, which is 'Alex' in this case.

❖ "multi" Parameter while updating multiple documents

To update multiple documents in a collection, set the multi option to true.

db.collection.update(
query,
update,
{
upsert: boolean,
multi: boolean,
writeConcern: document
}
)
➔ multi is optional. If set to true, updates multiple documents that meet the query criteria.
If set to false, updates one document. The default value is false.

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB

db.mycol.find() { "_id" : ObjectId(598354878df45ec5), "title":"MongoDB Overview"} { "_id" :


ObjectId(59835487adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(59835487adf45ec7),
"title":"Tutorials Point Overview"}

db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},{multi:true})

❖ Update of embedded documents.


- For the following schema: {name: 'Tom', age: 28, marks: [50, 60, 70]}

Update Tom's marks to 55 where marks are 50 (Use the positional operator $):

db.people.update({name: "Tom", marks: 50}, {"$set": {"marks.$": 55}})

- For the following schema: {name: 'Tom', age: 28, marks: [{subject: "English", marks:
90},{subject: "Maths", marks: 100}, {subject: "Computes", marks: 20}]}

Update Tom's English marks to 85:

db.people.update({name: "Tom", "marks.subject": "English"},{"$set":{"marks.$.marks": 85}})

// By using {name: "Tom", "marks.subject": "English"} you will get the position of the object in the

marks array, where subject is English. In "marks.$.marks", $ is used to update in that position of

the marks array.

- Update Values in an Array

The positional $ operator identifies an element in an array to update without explicitly specifying

the position of the element in the array.

Consider a collection students with the following documents:

{ "_id" : 1, "grades" : [ 80, 85, 90 ] }

{ "_id" : 2, "grades" : [ 88, 90, 92 ] }

{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

To update 80 to 82 in the grades array in the first document, use the positional $ operator if you do

not know the position of the element in the array:

db.students.update(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } })

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB

II. Work to be done


1. Start with MongoDB

To manipulate a database with Mongo Shell:


- Open a terminal and run the “mongosh” command to launch MongoDB as a client.
- Use the “show bds” command to display the databases that exist by default.
- Use the command "use name_base" to open a database. If the database does not exist, it will be
created.
- A database can be displayed if it contains at least one collection. To add a collection to a database,
we use the command: db. nom_collection . insert ({ }).
2. Manipulating a MongoDB database using Mongo Shell
- Create a database named “RestaurantManagement” containing a collection named “Restaurants”.
- Create a first document describing a first restaurant like following:

Building: 1007 “Bakery”

Address Coord -73.856077 borough: Cuisine: …..


40.848447 “Bronx”
Street: “Morris Park Ave”
Zip_code: 10462
Grade: “A”
Score: 2
grades Grade: “A” Name: Restaurant_id:
Score: 6 “Morris Park Bake
Grade: “B” Shop” 30075445
Score: 14

{
"address": {
"building": "1007",
"coord": [-73.856077, 40.848447],
"street": "Morris Park Ave",
"zipcode": "10462"
},

"borough": " Bronx",

"cuisine": "Bakery",
"grades": [ {
"grade": "A",
"score": 2

©Dr. Kalthoum Zaouali 2022-2023


Lab 6
NoSQL Database: Document Store using MongoDB
},
{
"grade": "A",
"score": 6
},
{
"grade": "B",
"score": 14
}],

"name": "Morris Park Bake Shop",


"restaurant_id": "30075445"
}

- Check the insertion of the document using the function count () to count the number of documents
in a collection. (db.collectionName.count()).
- Insert documents described in the file “Lab_Restaurants” in the collection “Restaurant”.
- Propose the appropriate queries to respond to following requests:
1. Show restaurants located in the Brooklyn area (borough= “Brooklyn”).
2. Show only the names and addresses of these restaurants.
3. Determine the names of restaurants with the cuisine type "Bakery" and located in "Brooklyn" area.
4. Determine the names of restaurants that have the cuisine type "Bakery" or are in the "Brooklyn" area.
5. Determine the names of the restaurants having as type of cuisine "Ice Cream", "Yogurt" or
"Hamburgers".
6. Determine the names of the restaurants that necessarily have "Ice Cream" and "Yogurt" as their type of
cuisine.
7. Determine the names of restaurants in the "Brooklyn" area that do not have "Hamburgers" as their type
of cuisine.
8. Determine the names of restaurants that do not have any grades.
9. Determine the names of the restaurants that did not obtain grades of type "B" and "Z".
10. Determine the names of the restaurants having obtained grades between 10 and 14.
11. Determine the names of restaurants with "B" grades and grades > 10.
12. For all the restaurant located in the Brooklyn area and having “A” as grade, change their score to 5.
13. Delete all the restaurant having a score >10.

©Dr. Kalthoum Zaouali 2022-2023

You might also like