Assignment No 11 Study of Mongodb Command - 181021004
Assignment No 11 Study of Mongodb Command - 181021004
BRANCH: Mechanical
ID: 181021004
QUESTIONS:
QUERIES
Click to connect
Connecting...
1 | Page
Implicit session: session { "id" : UUID("c3bb796e-540e-42bc-bf98-983e712459ef") }
admin 0.000GB
config 0.000GB
local 0.000GB
>>> db.createCollection("games")
{ "ok" : 1 }
"acknowledged" : true,
"insertedIds" : [
ObjectId("618eac5b3987e479f56d11f8"),
ObjectId("618eac5b3987e479f56d11f9"),
ObjectId("618eac5b3987e479f56d11fa"),
ObjectId("618eac5b3987e479f56d11fb"),
ObjectId("618eac5b3987e479f56d11fc")
2 | Page
}
>>> db.games.find()
>>> db.games.find().pretty()
"_id" : ObjectId("618eac5b3987e479f56d11f8"),
"rating" : 97
"_id" : ObjectId("618eac5b3987e479f56d11f9"),
"genre" : "Family",
"rating" : 93
3 | Page
"_id" : ObjectId("618eac5b3987e479f56d11fa"),
"genre" : "Strategy",
"rating" : 95
"_id" : ObjectId("618eac5b3987e479f56d11fb"),
"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)
>>> })
>>> db.games.find()
5 | Page
"Game Master", "Speed Demon" ] }
"_id" : ObjectId("618eac5b3987e479f56d11fb"),
"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"
"_id" : ObjectId("618eac5b3987e479f56d11fb"),
"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.
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.
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.
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
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:
--------------------------------------------------------------------------------------------------------------------
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" }
]);
----------------------------------------------------------------------------------------------------
Specify OR Conditions
SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE
"p%")
15 | Page
The following methods can also add new documents to a collection:
-------------------------------------------------------------------------------------------------------------------
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
{
...
Some update operators, such as $set, will create the field if the field does not exist.
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" }, {
})
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
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(
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
You can specify criteria, or filters, that identify the documents to delete. The filters use the same
syntax as read operations.
{ <field1>: <value1>, ... }
The following example deletes all documents from the inventory collection
db.inventory.deleteMany({})
*******************************************xxxxxxxxx*************************
*
18 | Page
Match an Array
db.inventory.insertMany([
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
]);
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:
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:
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:
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.
*******************************************xxxxxxxxx*************************
*
20 | Page