0% found this document useful (0 votes)
202 views20 pages

Assignment No 11 Study of Mongodb Command - 181021004

The document describes a lab assignment to learn MongoDB commands. The goals are to learn how to install MongoDB, create collections to store documents, and use common MongoDB shell commands to manage documents. Key commands covered include Create, Read, Update, and Delete (CRUD) operations. The document also discusses why MongoDB is useful for storing flexible, schema-free JSON documents and when it may not be suitable, such as for highly relational data requiring joins.

Uploaded by

Shivpriya Amale
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)
202 views20 pages

Assignment No 11 Study of Mongodb Command - 181021004

The document describes a lab assignment to learn MongoDB commands. The goals are to learn how to install MongoDB, create collections to store documents, and use common MongoDB shell commands to manage documents. Key commands covered include Create, Read, Update, and Delete (CRUD) operations. The document also discusses why MongoDB is useful for storing flexible, schema-free JSON documents and when it may not be suitable, such as for highly relational data requiring joins.

Uploaded by

Shivpriya Amale
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/ 20

ASSIGNMENT 12(SUBJECT: DBMS)

(Please use this format for doing assignments)//

SUBMISSION DATE: 18/11/2021

NAME OF STUDENT: Shivpriya Sanjay Amale

BRANCH: Mechanical

ID: 181021004

Mongodb Web Shell for Execution: https://mws.mongodb.com/?version=3.6

QUESTIONS:

A. Create a collection called ‘games’.


B. Add 5 games to the database. Give each document the following properties: name, genre, rating
(out of 100).
C. Write a query that returns all the games
D. Write a query to find one of your games by name without using limit(). Use the findOne
method.
E. Write a query that returns the 3 highest rated games.
F. Update your two favourite games to have two achievements called ‘GameMaster’ and ‘Speed
Demon’, each under a single key. Show two ways to do this. Do the first using update() and do the
second using save() . Hint: for save, you might want to query
the object and store it in a variable first.
G. Write a query that returns all the games that have both the ‘Game Master’ and the ‘Speed
Demon’ achievements.
H. Write a query that returns only games that have achievements. Not all of your games should
have achievements, obviously.

QUERIES

MongoDB Web Shell

Click to connect

Connecting...

MongoDB shell version v3.6.23

connecting to: mongodb://127.0.0.1:27017/?authSource=admin&gssapiServiceName=mongodb

1 | Page
Implicit session: session { "id" : UUID("c3bb796e-540e-42bc-bf98-983e712459ef") }

MongoDB server version: 3.6.23

type "help" for help

>>> show dbs

admin 0.000GB

config 0.000GB

local 0.000GB

>>> use vGames

switched to db vGames2 | Page

>>> db.createCollection("games")

{ "ok" : 1 }

>>> db.games.insertMany([{name:"Grand Theft Auto" , genre:"Open World" ,rating:97} ,


{name:"Super Mario" ,

genre:"Family" ,rating:93},{name:"Command And Conquer" , genre:"Strategy" ,


rating:95},{name:"FIFA 22" ,

genre:"Sports" , rating:99},{name:"Minecraft" , genre:"Sandbox" , rating:98}])

"acknowledged" : true,

"insertedIds" : [

ObjectId("618eac5b3987e479f56d11f8"),

ObjectId("618eac5b3987e479f56d11f9"),

ObjectId("618eac5b3987e479f56d11fa"),

ObjectId("618eac5b3987e479f56d11fb"),

ObjectId("618eac5b3987e479f56d11fc")

2 | Page
}

>>> db.games.find()

{ "_id" : ObjectId("618eac5b3987e479f56d11f8"), "name" : "Grand Theft Auto", "genre" :


"Open World", "rating" : 97 }

{ "_id" : ObjectId("618eac5b3987e479f56d11f9"), "name" : "Super Mario", "genre" : "Family",


"rating" : 93 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fa"), "name" : "Command And Conquer", "genre" :


"Strategy", "rating" : 95 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fb"), "name" : "FIFA 22", "genre" : "Sports",


"rating" : 99 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fc"), "name" : "Minecraft", "genre" : "Sandbox",


"rating" : 98 }

>>> db.games.find().pretty()

"_id" : ObjectId("618eac5b3987e479f56d11f8"),

"name" : "Grand Theft Auto",

"genre" : "Open World",

"rating" : 97

"_id" : ObjectId("618eac5b3987e479f56d11f9"),

"name" : "Super Mario",

"genre" : "Family",

"rating" : 93

3 | Page
"_id" : ObjectId("618eac5b3987e479f56d11fa"),

"name" : "Command And Conquer",

"genre" : "Strategy",

"rating" : 95

"_id" : ObjectId("618eac5b3987e479f56d11fb"),

"name" : "FIFA 22",

"genre" : "Sports",

"rating" : 99

"_id" : ObjectId("618eac5b3987e479f56d11fc"),

"name" : "Minecraft",

"genre" : "Sandbox",

"rating" : 98

>>> db.games.findOne({name:"Minecraft"})

{3 | Page

"_id" : ObjectId("618eac5b3987e479f56d11fc"),

"name" : "Minecraft",

"genre" : "Sandbox",

"rating" : 98

4 | Page
>>> db.games.find().sort({rating:-1}).limit(3)

{ "_id" : ObjectId("618eac5b3987e479f56d11fb"), "name" : "FIFA 22", "genre" : "Sports",


"rating" : 99 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fc"), "name" : "Minecraft", "genre" : "Sandbox",


"rating" : 98 }

{ "_id" : ObjectId("618eac5b3987e479f56d11f8"), "name" : "Grand Theft Auto", "genre" :


"Open World", "rating" : 97 }

>>> db.games.update({name:"Minecraft"},{$set:{achievement:["Game Master","Speed


Demon"]}

>>> })

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

>>> db.games.save({"_id":ObjectId(618eac5b3987e479f56d11fb) , name: "FIFA 22", genre :


"Sports", rating : 99,

achievement:["Game Master" , "Speed Demon"] })

2021-11-12T18:07:10.163+0000 E QUERY [thread1] SyntaxError: missing exponent


@(shell):1:30

>>> db.games.save({"_id":ObjectId("618eac5b3987e479f56d11fb") , name: "FIFA 22", genre :


"Sports", rating : 99,

achievement:["Game Master" , "Speed Demon"] })

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

>>> db.games.find()

{ "_id" : ObjectId("618eac5b3987e479f56d11f8"), "name" : "Grand Theft Auto", "genre" :


"Open World", "rating" : 97 }

{ "_id" : ObjectId("618eac5b3987e479f56d11f9"), "name" : "Super Mario", "genre" : "Family",


"rating" : 93 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fa"), "name" : "Command And Conquer", "genre" :


"Strategy", "rating" : 95 }

{ "_id" : ObjectId("618eac5b3987e479f56d11fb"), "name" : "FIFA 22", "genre" : "Sports",


"rating" : 99, "achievement" : [

5 | Page
"Game Master", "Speed Demon" ] }

{ "_id" : ObjectId("618eac5b3987e479f56d11fc"), "name" : "Minecraft", "genre" : "Sandbox",


"rating" : 98, "achievement" : [

"Game Master", "Speed Demon" ] }

>>> db.games.find({achievement:{$eq:["Game Master", "Speed Demon"]}})

{ "_id" : ObjectId("618eac5b3987e479f56d11fb"), "name" : "FIFA 22", "genre" : "Sports",


"rating" : 99, "achievement" : [

"Game Master", "Speed Demon" ] }

{ "_id" : ObjectId("618eac5b3987e479f56d11fc"), "name" : "Minecraft", "genre" : "Sandbox",


"rating" : 98, "achievement" : [

"Game Master", "Speed Demon" ] }

>>> db.games.find({achievement:{$eq:["Game Master", "Speed Demon"]}}).pretty()

"_id" : ObjectId("618eac5b3987e479f56d11fb"),

"name" : "FIFA 22",

"genre" : "Sports",

"rating" : 99,

"achievement" : [

"Game Master",

"Speed Demon"

"_id" : ObjectId("618eac5b3987e479f56d11fc"),

"name" : "Minecraft",

6 | Page
"genre" : "Sandbox",

"rating" : 98,

"achievement" : [

"Game Master",

"Speed Demon"

>>> db.games.update({name:"Minecraft"},{$set:{achievement:["Speed Demon"]} })

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })4 | Page

>>> db.games.find({achievement:{$eq:["Game Master", "Speed Demon"]}})

{ "_id" : ObjectId("618eac5b3987e479f56d11fb"), "name" : "FIFA 22", "genre" : "Sports",


"rating" : 99, "achievement" : [

"Game Master", "Speed Demon" ] }

>>> db.games.find({achievement:{$in:["Game Master", "Speed Demon"]}}).pretty()

"_id" : ObjectId("618eac5b3987e479f56d11fb"),

"name" : "FIFA 22",

"genre" : "Sports",

"rating" : 99,

"achievement" : [

"Game Master",

"Speed Demon"

7 | Page
{

"_id" : ObjectId("618eac5b3987e479f56d11fc"),

"name" : "Minecraft",

"genre" : "Sandbox",

"rating" : 98,

"achievement" : [

"Speed Demon”

OUTPUT SNAPSHOTS:

8 | Page
9 | Page
AIM: Study of Mongodb Commands
Mongob is one of the most used, open-source document database, and NoSQL database. MongoDB is
developed by 10gen. It is written in C++ and it is a document-oriented database. It uses BSON format.

In this lab we will learn. How to install MongoDB, How to create new collections that store documents,
You'll learn about the most common and used MongoDB shell commands to manage your documents.
We will cover the different types of data that can be stored. You will gain confidence in how to preform
CRUD operations i.e. Create, Read, Update and Delete data.
Installation in Linux:
> sudo apt-get install mongodb
> sudo apt-get update
> sudo service mongodb start
> mongo
Mongo DB is a highly scalable, NoSQL, schema free data store.

Here's why it's great


● It stores data as JSON so you can use the same data clientside and serverside. This means you
write almost no wiring code, everything just works.
● Flexible Schema. If your requirements change, you can adapt.
● Unstructured data - you can store and retrieve unstructured data easily. It's just JSON. Not
every document in a collection needs the same fields.
● Denormalised data - Group related content in a single document.
● Clean and simple API - Mongo is nice to talk to.

Here's why you might not like it


● Denormalised data means no joins. If your data is highly relational, Mongo is not of your use.
Your data is organised into collections. If you need data from more than collection, you need
to hit the database more than once.

10 | Page
● Flexible schema means no built in data validation. Your data is validated at the application tier.
The database is dumb and will store whatever your application gives it, even junk and typos.
● Bugs - Mongo is new and there are still issues in the tracker. Not bad bugs, but occasionally
things don't work as you might expect.

● No transactions - A SQL database allows you to bundle multiple writes into a transaction. If
one write fails the whole transaction is rolled back. Mongo lacks this feature; writes are small
and atomic. If you need a transaction you must build it yourself.
● Theoretical data loss - Mongo scales using a technique called sharding. It creates slaves that
mirror data written to the master. If the master goes down before data is mirrored you may lose
recent commits depending on your settings.

When you should use it


Mongo represents data as a tree. If your data is tree shaped, or can be made tree shaped, Mongo is
great. If your data is a web or a network which can't be flattened out, you likely have relational data,
and Mongo is perhaps not for you this time.

If you have unstructured data to store which can be represented as a series of nested lists Mongo will
make your life more enjoyable.

Say you have a webpage full of widgets, and each of those widgets can contain arbitrary information.
This is a semi-structured tree and Mongo might be a very good choice.

If you have big customer data to store, and each customer record contains lists of communications,
subscriptions, etc, the data is tree shaped, and Mongo would again be a good choice.

If you have big data and you want to query it in interesting and complex ways, pulling useful aggregated
data out the other side in suprisingly short timeframes, Mongo is perfect.

On the other hand, if your data looks like a web: comments, purchases, kittens, customers, sharks,
exploding hats, etc, all linking to each other in a web, then you have relational data, and you may wish
to stick with a relational database like Postgres, MySQL or MS SQL Server.

Why is it fast?
Mongo manages to be so fast because it does less. There's no magical difference in the architecture
that makes it fast, it just has a simplified streamlined query language that is easier to optimise.

The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mongo shell to
query and update data as well as perform administrative operations.

The mongo shell is included as part of the MongoDB Server installation. MongoDB also provides the
mongo shell as a standalone package.

11 | Page
> db #displays the database we are using, by default displays test
> Use test1
> show dbs #displays all dbs

>use myNewDatabase #creates database if doesnt exist. When you first store data in the database, such
as by creating a collection, MongoDB creates the database. For example, the following creates both
the database myNewDatabase and the collection myCollection during the insertOne() operation >
db.dropDatabase() #db refers to the current database.

Collections
Collections are sets of (usually) related documents. Your database can have as many collections as
you like.

Because Mongo has no joins, a Mongo query can pull data from only one collection at a time. You
will need to take this into account when deciding how to arrange your data.

You can create a collection using the createCollection command.

> use petshop


> db.createCollection('mammals')
> show collections
Collections will also be created automatically. If you write a document to a collection that doesn't
exist that collection will be brought into being for you.

Documents
Documents are JSON objects that live inside a collection. They can be any valid JSON format, with
the caveat that they can't contain functions.

The size limit for a document is 16Mb which is more than ample for most use cases.

Creating a document
You can create a document by inserting it into a collection

> db.mammals.insert({name: "Polar Bear"})


> db.mammals.insert({name: "Star Nosed Mole"})

12 | Page
Finding a document
You can find a document or documents matching a particular pattern using the find function.

If you want to find all the mammals in the mammals collection, you can do this easily.

> db.mammals.find()

> db.mammals.find().toArray();
> db.mammals.find().pretty();

Finding documents
Mongo comes with a set of convenience functions for performing common operations. Find is one
such function. It allows us to find documents by providing a partial match, or an expression.

Uses
You can use find to:

● Find a document by id
● Find a user by email
● Find a list of all users with the same first name
● Find all cats who are more than 12 years old
● Find all gerbils called 'Herbie' who are bald, have three or more eyes, and who have exactly 3
legs.

Limitations
You can't use find to chain complex operators. You can do a few simple things like counting, but if
you want to real power you need the aggregate pipeline, which is actually not at all scary and is quite
easy to use.

The Aggregate pipeline allows us to chain operations together and pipe a set of documents from one
operation to the next.

Using find
You can use find with no arguments to list documents in a collection.

13 | Page
Mongodb Lab Execution

CRUD Operations

Installation in Linux:
> sudo apt-get install mongodb
> sudo apt-get update
> sudo service mongodb start
> mongo

>db
>show dbs
> use dbs_name > use test
> db.dropDatabase()
> db.createCollection('inventory')
> show collections
>db.users.drop()
--------------------------------------------------------------------------------------------------------------------
-
>db.collection.insert() inserts a single document or multiple documents into a collection.
>db.collection.insertOne() inserts a single document into a collection.

OR
>db.inventory.insertOne({ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5,
uom: "cm" }})

The following example inserts a new document into the inventory collection. If the document
does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new
document.

--------------------------------------------------------------------------------------------------------------------
-
To retrieve the document that you just inserted, query the collection:

>db.inventory.find() equals to Select * from inventory


> db. inventory.find().toArray()
> db. inventory.find().pretty()
>db.collection.findOne() //returns one document
>db.inventory.find( { item: "canvas" } ) OR Select * from inventory where item = “canvas”

--------------------------------------------------------------------------------------------------------------------

14 | Page
db.collection.insertMany() can insert multiple documents into a collection. Pass an array of
documents to the method.

db.inventory.insertMany([

{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

]);

----------------------------------------------------------------------------------------------------

Count the number of documents stored in providers collection


db.providers.find().count()

db.inventory.find( { status: { $in: [ "A", "D" ] } } )

SELECT * FROM inventory WHERE status in ("A", "D")

db.inventory.find( { status: "A", qty: { $lt: 30 } } )

SELECT * FROM inventory WHERE status = "A" AND qty < 30

Specify OR Conditions

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

SELECT * FROM inventory WHERE status = "A" OR qty < 30

Specify AND as well as OR Conditions

db.inventory.find( {status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]} )

SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE
"p%")

Additional Methods for Inserts

15 | Page
The following methods can also add new documents to a collection:

● db.collection.update() when used with the upsert: true option.


● db.collection.updateOne() when used with the upsert: true option.
● db.collection.updateMany() when used with the upsert: true option.
● db.collection.findAndModify() when used with the upsert: true option.
● db.collection.findOneAndUpdate() when used with the upsert: true option.
● db.collection.findOneAndReplace() when used with the upsert: true option.
● db.collection.save().
● db.collection.bulkWrite().

-------------------------------------------------------------------------------------------------------------------

Update Documents

db.inventory.insertMany( [

{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },

{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },

{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },

{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },

{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },

{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }

] );

To update a document, MongoDB provides update operators, such as $set, to modify field
values.

To use the update operators, pass to the update methods an update document of the form:

16 | Page
{

<update operator>: { <field1>: <value1>, ... },

<update operator>: { <field2>: <value2>, ... },

...

Some update operators, such as $set, will create the field if the field does not exist.

Update a Single Document

The following example uses the db.collection.updateOne() method on the inventory collection to
update the first document where item equals "paper":

db.inventory.updateOne(

{ item: "paper" }, {

$set: { "size.uom": "cm", status: "P" },

$currentDate: { lastModified: true }

})

The update operation:

uses the $set operator to update the value of the size.uom field to "cm" and the value of the status
field to "P",

uses the $currentDate operator to update the value of the lastModified field to the current date. If
lastModified field does not exist, $currentDate will create the field. See $currentDate for details

Update Multiple Documents

The following example uses the db.collection.updateMany() method on the inventory collection
to update all documents where qty is less than 50:

db.inventory.updateMany(

{ "qty": { $lt: 50 } },{$set: { "size.uom": "in", status: "P" }, $currentDate: {


lastModified: true }})

17 | Page
The update operation:

uses the $set operator to update the value of the size.uom field to "in" and the value of the status
field to "P",

uses the $currentDate operator to update the value of the lastModified field to the current date. If
lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

Replace a Document

To replace the entire content of a document except for the _id field, pass an entirely new
document as the second argument to db.collection.replaceOne().

When replacing a document, the replacement document must consist of only field/value pairs;
i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the
replacement document, you can omit the _id field since the _id field is immutable; however, if
you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item:
"paper":

db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40
} ] })
Delete Documents

Delete All Documents that Match a Condition

You can specify criteria, or filters, that identify the documents to delete. The filters use the same
syntax as read operations.
{ <field1>: <value1>, ... }

db.inventory.deleteMany({ status : "A" })

Delete Only One Document that Matches a Condition


db.inventory.deleteOne( { status: "D" } )

The following example deletes all documents from the inventory collection
db.inventory.deleteMany({})
*******************************************xxxxxxxxx*************************
*

18 | Page
Match an Array

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },

{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },

{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },

{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },

{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }

]);

The following example queries for all documents where the field tags value is an array with exactly
two elements, "red" and "blank", in the specified order:

db.inventory.find( { tags: ["red", "blank"] } )

Find an array that contains both the elements "red" and "blank", without regard to order or other
elements in the array, use the $all operator:

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

Query for an Element by the Array Index Position

Using dot notation, you can specify query conditions for an element at a particular index or
position of the array. The array uses zero-based indexing.

The following example queries for all documents where the second element in the array dim_cm is
greater than 25:

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

19 | Page
Query an Array by Array Length

Use the $size operator to query for arrays by number of elements. For example, the following
selects documents where the array tags has 3 elements.

db.inventory.find( { "tags": { $size: 3 } } )

Import a JSON file

mongoimport --db vjti --collection restaurants --drop –file


~C:\Users\ShraddhaSuratkar\Downloads\restaurants.json

*******************************************xxxxxxxxx*************************
*

*******End of the Assignment*******

20 | Page

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy