MONGODBINSTLLATION and LAB MANUAL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Aim: Install & study MongoDB and Implement CRUD Operations.

Problem Statement: Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD
operations, Execution)

Objective:
1. To learn and understand NOSQL Database.
2. To execute CRUD Operations on MongoDB.

Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Ubuntu 14.04, Mongodb Packages Theory: MongoDB is a free and open-
source NoSQL document database used commonly in modern web applications. MongoDB works on
concept of collection and document.
Installation-

Download & Install MongoDB on Windows

Step 1) Go to https://www.mongodb.com/try/download/community and Download MongoDB


Community Server. We will install the 64-bit version for Windows.

Step 2) Once download is complete open the msi file. Click Next in the start up screen
Step 3) 

1. Accept the End-User License Agreement


2. Click Nest
Step 4) Click on the "complete" button to install all of the components. The custom option can be
used to install selective components or if you want to change the location of the installation.

Step 5) 

1. Select “Run service as Network Service user”. make a note of the data directory, we’ll need
this later.
2. Click Next
Step 6) Click on the Install button to start the installation.

Step 7) Installation begins. Click Next once completed


Step 8) Click on the Finish button to complete the installation

Step 9) Go to " C:\Program Files\MongoDB\Server\4.0\bin" and double click on mongo.exe


Alternatively, you can also click on the MongoDB desktop item
Collection –
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection
exists within a single database. Collections do not enforce a schema.
Document – Collection-documents-Key_value pair
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means
that documents in the same collection do not need to have the same set of fields or structure, and
common fields in a collection's documents may hold different types of data.
CRUD Operations:
CRUD operations create, read, update, and delete documents.
These operations are considered to be the four basic functionalities of a repository .
CRUD operations can be mapped directly to database operations:

 Create matches insert


 Read matches select
 Update matches update
 Delete matches delete
Create Operations
Create or insert operations add new documents to a collection. If the collection does not currently
exist, insert operations will create the collection.
db.collection.insert()
Syntax:
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
e.g.
1) db.products.insert( { item: "card", qty: 15 } )
Will store record(document) as
{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }
2) db.products.insert( { _id: 10, item: "box", qty: 20 } )
Will store record (document) as
db.products.insert( { _id: 10, item: "box", qty: 20 } )

db.products.insert( { "_id" : 1, "sem" : 1, "achieve" : [ 70, 87, 90 ] })array insert

Read Operations
Read operations retrieves documents from a collection; i.e. queries a collection for documents.
MongoDB provides the following methods to read documents from a collection:
db.collection.find()
You can specify query filters or criteria that identify the documents to return.
Examples
Find All Documents in a Collection
The find() method with no parameters returns all documents from a collection and returns all fields
for the documents. For example, the following operation returns all documents in the bios collection:
db.bios.find()
Find Documents that Match Query Criteria
To find documents that match a set of selection criteria, call find() with the <criteria> parameter. The
following operation returns all the documents from the collection products where qty is greater than
25:
db.products.find( { qty: { $gt: 25 } } )

Update Operations
MongoDB Update() Method:
The update() method updates the values in the existing document.
Syntax The basic syntax of update() method is as follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Example Consider the mycol collection has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" :
ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" :
ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is
'MongoDB Overview'.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
>db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" :
ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} >
By default, MongoDB will update only a single document. To update multiple documents, you need
to set a parameter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},
{multi:true})

Delete Operation:
The remove() Method MongoDB's remove() method is used to remove a document from the
collection. remove() method accepts two parameters. One is deletion criteria and second is justOne
flag.
deletion criteria − (Optional) deletion criteria according to documents will be removed.
justOne − (Optional) if set to true or 1, then remove only one document.
Syntax Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example Consider the mycol collection has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" :
ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" :
ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" :
ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} >
Remove Only One If there are multiple records and you want to delete only the first record, then set
justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Remove All Documents If you don't specify deletion criteria, then MongoDB will delete whole
documents from the collection. This is equivalent of SQL's truncate command.
>db.mycol.remove() >db.mycol.find() >
Using Modifiers
1. $set- sets the value of a field

In MongoDB, the $set operator is used to replace the value of a field to the specified value. If the
given field does not exist in the document, the $set operator will add the field to the specified
value.

Syntax:

{ $set: { <field1>: <value1>, ... } }


Eg. >db.employeeset.update( { emp_id: 1231 },{ $set: {"email": "jonesalan@mytestmail.com"}})
2. $unset- unsets or remove the key

In MongoDB, the $unset operator is used to delete a particular field. The value specified in the
$unset expression does not make any impact on the operation. The $unset has no effect when the
field does not exist in the document.

Syntax:

{ $unset: { <field1>: "", ... } }


Parameters:

Our database name is 'myinfo' and our collection name is "items1".

{ "_id" : 1, "description" : "item1", "op_stock" : 100, "purqty" : 100 }

Example of MongoDB $unset operator to delete field from first matching document

If we want to delete the purqty field from the document for _id is 1 the following mongodb
command can be used-

>db.items1.update( { _id: 1 },{ $unset: {"purqty": ""}})


3. $inc- to change the values of a field or to create a new field if it does not exist ( not
applicable for non number)

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The
$inc operator adds as a new field when the specified field does not exist, and sets the field to the
specified amount. The $inc accepts positive and negative value as an incremental amount.

Syntax:

{ $inc: { <field1>: <amount1>, ... } }


If we want to increment the value of qty by 10 for the first matching document in the collection
items for item_id is I001 the following mongodb statement can be used:

> db.items.update( { item_id: "I001" },{ $inc: { qty: 10 }});

4. $push- adding element to array

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned
field is absent in the document to update, the $push operator add it as a new field and includes
mentioned value as its element. If the updating field is not an array type field the operation failed.

At the time of updating if the value itself is an array, the $push operator appends the whole array as
a single element.

If you want to add each element of the value separately, the $push operator can be used with the
$each modifier.

Syntax:

db.collection.update( <query>,{ $push: { <field>: <value> } })


If we want to append 95 to the array field achieve against the condition subjects is "gkn", the
following mongodb command can be used -

> db.student.update( { "subjects" : "gkn" },{ $push: { "achieve": 95 } });

Copy
Here in the above example the value 95 will be append into the array achieve, because the condition
mentioned is matching for this operation.

5. $each- adding multiple values in array in one operation

If we want to append multiple elements or more than one elements (77,49,83 ) to the
array achieve for the document student for the condition subjects is "gkn", the following mongodb
command can be used -
> db.student.update( { "subjects" : "gkn" },{ $push: { "achieve": {$each : [77,49,83 ]} } });

Here in the above example the $each modifier have used to append multiple elements 77,49,83 to
the array achieve which matches the condition subjects equals "gkn".

6. $addtoSet- adding element to an array

The $addToSet operator adds or appends a value to an array, only if the value does not exist in the
array. The $addToSet returns the same array without modifying when the value already is in the
array.

The $addToSet operator ensures that there will be no duplicate items in an array at the time of
updating, but one thing can be happen that, after adding a value, the order of the elements of an
array can be changed.

Syntax:

db.collection.update( { <field>: <value> }, { $addToSet: { <field>: <addition> } } )


{ "_id" : 1, "sem" : 1, "achieve" : [ 70, 87, 90 ] }

7. $pop- removes elements from array


l {“$pop”: {“key” : 1}} removes an element from the end of the array.

l {“$pop”: {“key” : -1}} removes an element from the beginning of the array.

8. $pull- used to remove an element of an array that match the given criteria

In MongoDB, the $pull operator is used to removing all instances of a value from an existing array.

Syntax:

db.collection.update( { field: <query> }, { $pull: { field: <query> } } );


If we want to remove the element "maths" from the the array field subjects for any instance in this
array is "maths", the following mongodb command can be used -

> db.student.update( { "subjects" : "maths" }, { $pull: { "subjects": "maths" }} );


MongoDB Upsert

A upsert is special type of update. If no document is found that matches the update criteria, a new
document will be created by combining the criteria & updated documents.
Third parameter to update specifies that this should be an upsert.
> db.coll.update({“url”: “/blog”}, {“$inc” : “pageviews”:1}}, true)
Refer link
https://kb.objectrocket.com/mongo-db/mongodb-upsert-1405

Querying

 Find all doc where age = 27 and user name=joe


>db.user.find( {“username”:”joe”, “age”:27})

 Find user where age is greater than 20 and less than 30


>db.user.find({“age”: { “$gt”: 20, “$lt” : 30 }})

 Operators are used as

 $gte= greater than equal

 $lte=less than equal

 $ne=not equal

 $eq=equal

 $gt=greater than

 $lt= less than

 $and = and

 $or = or

 $not = not

 $first= first element of array

 $last= last element of array

 $size= gives size of array

 $all= matches all element of given array

 $in= is a member

 $exists= element exists or not

 $limit- will given subelement of array


Aggregation
Aggregation operations group values from multiple documents together, and can perform a
variety of operations on the grouped data to return a single result.
For the aggregation in mongodb you should use aggregate() method.

Aggregation in MongoDB is nothing but an operation used to process the data that returns the
computed results. Aggregation basically groups the data from multiple documents and operates in
many ways on those grouped data in order to return one combined result. In sql count(*) and
with group by is an equivalent of MongoDB aggregation.
Aggregate function groups the records in a collection, and can be used to provide total number(sum),
average, minimum, maximum etc out of the group selected.
In order to perform the aggregate function in MongoDB, aggregate () is the function to be used.
Following is the syntax for aggregation :

db.collection_name.aggregate(aggregate_operation)

Let us now see how to make use of the aggregate function in MongoDB. Consider a collection
named books
Now, from the above collection, let us use the aggregate function to group the books which are of the
type ebook and online. Following command will be used :

db.books.aggregate([{$group : {_id: "$type", category: {$sum : 1}}}])

The above aggregate function will give result, which says there are 2 records of the type ebook and 2
records of the type online. So the above aggregation command, has grouped our collection data, based
on their type.

 count()- gives total doc of collection


o >db.user.count()

 Aggregation Framework:

 $project- to display particular key and key value


o Ex: >db.user.aggregate(“$project”,{“author” : 1}) it displays the document with
author only

 $group-
o Ex. >db.user.aggregate(“$group”, {“_id” : “author”})

 $sort- to sort the documents


o Ex. >db.user.aggregate(“$sort”, {“author”: -1})
 -1 means sort in descending order
o $limit- display only first or last document

o Ex. >db.user.aggregate(“$project”, {“author” : 1}, {“$limit” : 5})


Grouping in Mongo Aggregate
Group is used to group different things together. For example, if you want to calculate the sum of the
age of students in different standards, the query will look something like this.
db.students.aggregate([ { $group: { _id: "$class", total: { $sum: "$age" } } }])

Different expressions used by Aggregate function

Expression Description

$sum Summates the defined values from all the documents in a collection

$avg Calculates the average values from all the documents in a collection

$min Return the minimum of all values of documents in a collection

$max Return the maximum of all values of documents in a collection

$first Returns the first document from the source document

$last Returns the last document from the source document

You might also like