0% found this document useful (0 votes)
6 views51 pages

Soc-Ii Mongodb Record

The document provides an introduction to MongoDB, an open-source, document-oriented database that supports a rich query language and is designed for high-performance applications. It covers key features, installation steps on Windows, and the structure of databases, documents, and collections, highlighting the differences from traditional RDBMS. Additionally, it discusses various query and update operators used in MongoDB for data manipulation.

Uploaded by

Suneela Mathe
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)
6 views51 pages

Soc-Ii Mongodb Record

The document provides an introduction to MongoDB, an open-source, document-oriented database that supports a rich query language and is designed for high-performance applications. It covers key features, installation steps on Windows, and the structure of databases, documents, and collections, highlighting the differences from traditional RDBMS. Additionally, it discusses various query and update operators used in MongoDB for data manipulation.

Uploaded by

Suneela Mathe
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/ 51

SOC-II (MongoDB)

EXPERIMENT-1

Aim: Introduction to the MongoDB database.

1.Introduction to MongoDB

MongoDB is an Open Source database written in C++.Drivers and client libraries are
typically written in their respective languages, although some drivers use C extensions for
better performance. If the load increases, by adding more nodes (such as a computer), the
performance can be retained. It can be used to store data for very high-performance
applications (for example Foursquare is using it in production).MongoDB does not support
SQL It supports a rich, ad-hoc query language of its own.MongoDB stores data as
documents. So it is a document oriented database.

Example:

FirstName="Arun", Address="St. Xavier's Road", Spouse=[{Name:"Kiran"}],


Children=[{Name:"Rihit", Age:8}].
FirstName="Sameer",Address="8 Gandhi Road".

Notice there are two different documents (separated by "."). Storing data in this fashion is
called as document oriented database. MongoDB is a document oriented database.

Key Features:

Since MongoDB offers a Document oriented storage, It is simple and easily programmable.

 You can set an index on any attribute of a MongoDB record (as


FirstName="Sameer",Address="8 Gandhi Road"), with respect to which, a record can
be sort quickly and ordered.
 You can set mirror across local as well as wide area networks, which makes it easily
scalable.
 If load increases (more storage space, more processing power), it can be distributed to
other nodes across computer networks. This is called as sharding.
 MongoDB supports rich query to fetch data from the database.
 MongoDB supports replacing an entire document (database) or some specific fields
with it's update() command.
 MongoDB supports Map/Reduce framework for the batch processing of data and
aggregation operation. Here is brief of how Map/Reduce works :
 Map : A master node takes an input. Splits it into smaller sections. Sends it to the
associated nodes.

1
SOC-II (MongoDB)

 These nodes may perform the same operation in turn to send those smaller section of
input to other nodes. It processes the problem (taken as input) and sends it back to the
Master Node.
 Reduce : The master node aggregates those results to find the output.
 GridFS specification of MongoDB supports storage of very large files.
 MongoDB supports various programming languages like C, C# and .NET, C++,
Erlang, Haskell, Java, Javascript, Perl, PHP, Python, Ruby, Scala (via Casbah).
 It supports Server-side JavaScript execution. Which allows a developer to use a single
programming language for both client and server side code.
 MongoDB is easily installable.

History
Development of MongoDB began in October 2007 by 10gen. The first public release was in
February 2009.

Installation of MongoDB

You can download MongoDB from http://www.mongodb.org/downloads. As of this writing,


it supports following platforms:

 OS X 32-bit
 OS X 64-bit
 Linux 32-bit
 Linux 64-bit
 Windows 32-bit
 Windows 64-bit
 Solaris i86pc
 Solaris 64
 You can download the source and install MongoDB from that too.

MongoDB: Databases, Schemas, and Tables


Databases : MongoDB is a document-oriented DBMS, with JSON-like objects comprising
the data model, rather than RDBMS tables. MongoDB does not support joins nor
transactions. However, it features secondary indexes, an expressive query language, atomic
writes on a per-document level, and fully-consistent reads. MongoDB uses BSON, a binary
object format similar to, but more expressive than JSON.

2
SOC-II (MongoDB)

Schemas : MongoDB uses dynamic schemas. We can create collections without defining the
structure, i.e. the fields or the types of their values, of the documents. You can change the
structure of documents simply by adding new fields or deleting existing ones. Documents in a
collection need unique set of fields.

Tables : MongoDB database stores its data in collections not in tables The collections are the
rough equivalent of RDBMS tables. A collection holds one or more documents, which
corresponds to a record or a row in a relational database table, and each document has one or
more fields, which corresponds to a column in a relational database table.

3
SOC-II (MongoDB)

EXPERIMENT-2

Aim: Installation of MongoDB on Windows.

Install MongoDB on Windows


Steps to download MongoDB:

 Pre-built binary packages of MongoDB are available for both 32 bit and 64 bit. You
can download it, and install.

 Here is the link to download pre-built binary packages of MongoDB :


http://www.mongodb.org/downloads

 After downloading the zip file, unzip it to the folder where you want to install.

 MongoDB stores data in db folder within data folder. But, since this data folder is not
created automatically, you have to create it manually. Remember that data directory
should be created in the root (i.e. C:\ or D:\ or so).

 For this tutorial, we have unzipped it within mongodb folder within D: drive. Now, we
will create a folder called data and within that we will create a folder called db.

 It is not necessary to perform the above operation from the command prompt. You
may opt to do this from Windows Explorer also.

Run the MongoDB server From Command Prompt

 To run MongoDB server from the command prompt, you have to execute mongod.exe
file from bin folder of mongodb folder.

4
SOC-II (MongoDB)

Get Familiar with Mongo Shell:

To start an administrative shell, enter bin directory of your MongoDB installation and
execute mongo.exe file. The default administrative shell of MongoDB is a JavaScript shell.
When you connect MongoDB immediately after installation, it connects to the test document
(database).

Since it is a JavaScript Shell, you can run some simple arithmetic operation.

db command will show you the list of documents(databases).

We will insert a simple record and retrieve the data now.

The first command inserts 10 to the x field, to the w3r collection(table)

5
SOC-II (MongoDB)

EXPERIMENT-3

Aim: Get familiar with Mongo Shell.

Introduction to mongo Shell


Usage of multi-line operations in the mongo shell

If a line in mongo shell ends with an open parenthesis ('(') or an open brace ('{'), or an
open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the
corresponding closing parenthesis (')') or the closing brace ('}') or the closing bracket (']').
The mongo shell waits for the proper ending parenthesis before evaluating the code. Here is
the example below.

1 > if ( x > 0 ) {

2 ... count++;

3 ... print (x);

4 ... }

You can exit the line continuation mode if you enter two blank lines. Here is the example
below.

1 > if (x > 0

2 ...

3 ...

4>

Access different databases temporarily:

The db.getSiblingDB() method can be used to access another database without


switching databases, as in the following example which first switches to the mytest database
and then accesses the sampleDBdatabase from the test database:

1 use mytest

2 db.getSiblingDB('sampleDB').getCollectionNames();

Tab completion and keyboard shortcuts:

The mongo shell supports keyboard shortcuts. For example,

 Use the up/down arrow keys to scroll through command history.

6
SOC-II (MongoDB)

 Use <Tab> to autocomplete or to list the completion possibilities. Here in the example
below uses <Tab> to complete the method name starting with the letter 'd':

1 db.myCollection.c<Tab>

2 > db.myCollection.d

3 db.myCollection.dataSize( db.myCollection.drop(

4 db.myCollection.diskStorageStats( db.myCollection.dropIndex(

5 db.myCollection.distinct( db.myCollection.dropIndexes(

There are many collection methods starting with the letter 'd', the above example shows that
the <Tab> lists the various methods that start with 'd'.

Customize the mongo shell prompt:

You can change the mongo shell prompt by setting the prompt variable. This makes it
possible to display additional information in the prompt.Set prompt to any string or arbitrary
JavaScript code that returns a string, consider the following examples:

Set the shell prompt to display the hostname and the database issued:

1 > var host = db.serverStatus().host;

3 or you can use the constant for your host.

5 test@bidhan-PC> var host = "myhost";

6 test@myhost> var prompt = function() { return db+"@"+host+"> "; }

8 Here is the new mongo shell prompt.

10 test@myhost>

11

12 if you want to return the prompt again

13

7
SOC-II (MongoDB)

14 test@myhost> var prompt = function() { return "> "; }

Set the shell prompt to display the database statistics:

1 > var prompt = function() {

2 ... return "Uptime:"+db.serverStatus().uptime+"


Documents:"+db.stats().objects+" > "

3;

4 ... }

5 Here is the new prompt.

8 Uptime:9862 Documents:0 >

8
SOC-II (MongoDB)

EXPERIMENT-4

Aim: Creation of Databases, Documents and Collections in MongoDB.

Databases, documents and collections in MongoDB:


Databases

A number of databases can be run on a single MongoDB server. Default database of


MongoDB is 'db', which is stored within data folder.MongoDB can create databases on the
fly. It is not required to create a database before you start working with it."show dbs"
command provides you with a list of all the databases.

Run 'db' command to refer to the current database object or connection.

To connect to a particular database, run use command.

In the above command, 'student' is the database we want to select.

Database names can be almost any character in the ASCII range. But they can't
contain an empty string, a dot (i.e. ".") or " ".Since it is reserved, "system" can't be used as a
database name.A database name can contain "$".

Documents:

The document is the unit of storing data in a MongoDB database. document use JSON
(JavaScript Object Notation, is a lightweight, thoroughly explorable format used to
interchange data between various applications) style for storing data.

A simple example of a JSON document is as follows :

9
SOC-II (MongoDB)

{ site : "w3resource.com" }

Often, the term "object" is used to refer a document.Documents are analogous to the
records of an RDBMS. Insert, update, and delete operations can be performed on a collection.
The following table will help you to understand the concept more easily :

RDBMS MongoDB

Table Collection

Column Key

Value Value

Records / Rows Document / Object

Data Types Description

string May be an empty string or a combination of characters.

integer Digits.

boolean Logical values True or False.

double A type of floating point number.

null Not zero, not empty.

10
SOC-II (MongoDB)

array A list of values.

object An entity which can be used in programming. May be a value, variable,


function, or data structure.

timestamp A 64 bit value referring to a time and unique on a single "mongod"


instance. The first 32 bit of this value refers to seconds since the UTC
January 1, 1970. And last 32 bits refer to the incrementing ordinal for
operations within a given second.

Internationalized UTF-8 for strings.


Strings

Object IDs Every MongoDB object or document must have an Object ID which is
unique. This is a BSON(Binary JavaScript Object Notation, which is the
binary interpretation of JSON) object id, a 12-byte binary value which
has a very rare chance of getting duplicated. This id consists of a 4-byte
timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process
id, and a 3-byte counter.

The table shows the various datatypes which may be used in MongoDB.

Collections:

A collection may store a number of documents. A collection is analogous to a table of


an RDBMS.A collection may store documents those who are not same in structure. This is
possible because MongoDB is a Schema-free database. In a relational database like MySQL,
a schema defines the organization / structure of data in a database. MongoDB does not
require such a set of formula defining structure of data. So, it is quite possible to store
documents of varying structures in a collection. Practically, you don't need to define a
column and it's datatype unlike in RDBMS, while working with MongoDB.

In the following code, it is shown that two MongoDB documents, belongs to same
collection, storing data of different structures.

Example:

1 {"tutorial" : "NoSQL"}

11
SOC-II (MongoDB)

2 {"topic_id" : 7}

A collection is created, when the first document is inserted.

Pictorial Presentation : Collections and Documents

12
SOC-II (MongoDB)

EXPERIMENT-5

Aim: Query, Projection and update Operators

Comparison Query Operations

Name Description

$gt Matches values that are greater than the value specified in the query.

$lt Matches values that are less than the value specified in the query.

$gte Matches values that are greater than or equal to the value specified in the query.

$lte Matches values that are less than or equal to the value specified in the query.

$ne Matches all values that are not equal to the value specified in the query.

$in Matches any of the values that exist in an array specified in the query.

$nin Matches values that do not exist in an array specified in the query.

Logical Query operators

Name Description

$and Joins query clauses with a logical AND returns all documents that match the
conditions of both clauses.

$not Inverts the effect of a query expression and returns documents that do not match the
query expression.

13
SOC-II (MongoDB)

$or Joins query clauses with a logical OR returns all documents that match the
conditions of either clause.

$nor Joins query clauses with a logical NOR returns all documents that fail to match both
clauses.

Element Query operators

Name Description

$exists Matches documents that have the specified field.

$type Selects documents if a field is of the specified type.

Evaluation Query operators

Name Description

$mod Performs a modulo operation on the value of a field and selects documents with a
specified result.

$regex Selects documents where values match a specified regular expression.

$where Matches documents that satisfy a JavaScript expression.

Query operator Array

Name Description

14
SOC-II (MongoDB)

$all Matches arrays that contain all elements specified in the query.

$elemMatch Selects documents if an element in the array field matches all the specified
$elemMatch conditions.

$size Selects documents if the array field is a specified size.

Projection operator

Name Description

$ Projects the first element in an array that matches the query


condition.

$elemMatch(projection) Projects the first element in an array that matches the specified
$elemMatch condition.

$slice Limits the number of elements projected from an array. Supports


skip and limit slices.

MongoDB Field Update Operator - $inc


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>, ... } }


Parameters:

Name Description

15
SOC-II (MongoDB)

field1 name of the column or field

amount1 incremental value

Our database name is 'myinfo' and our collection name is "items". Here, is the
collection bellow.

Sample collection "items"

1{

2 "_id" : 1,

3 "item_id" : "I001",

4 "comp_id" : "C001",

5 "qty" : 25,

6 "prate" : 30,

7 "srate" : 35,

8 "mrp" : 40

9}

10 {

11 "_id" : 2,

12 "item_id" : "I001",

13 "comp_id" : "C002"

14 "qty" : 30,

15 "prate" : 32,

16 "srate" : 37,

17 "mrp" : 40

18 }

16
SOC-II (MongoDB)

Example of field update operator - $inc

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 }});

Here in the above example-

 The qty for the first matching document for the condition item_id is I001 have been
updated and the qty became 35 from 25 and the rest remains same.

To see the updated output -

> db.items.find().pretty();

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

Output of the command

{
"_id" : 1,
"item_id" : "I001",
"comp_id" : "C001",
"qty" : 35,
"prate" : 30,
"srate" : 35,
"mrp" : 40
}
{
"_id" : 2,
"item_id" : "I001",
"comp_id" : "C002",
"qty" : 30,
"prate" : 32,
"srate" : 37,
"mrp" : 40
}

17
SOC-II (MongoDB)

EXPERIMENT-6

Aim: Perform Aggregation pipeline operators in MongoDB.

MongoDB Aggregation Pipeline Operators


The MongoDB, aggregation pipeline is a framework for data aggregation modeled on
the concept of data processing pipelines. Documents enter as an input into multi-stage
pipeline which transforms the documents into an aggregated results.The MongoDB
aggregation pipeline consists various stages. Each stage transforms the documents passes
through the pipeline. In this stage it is not needed to produce one output document for every
input document. The pipeline stages can appear multiple times in the pipeline.Here is a list of
MongoDB Aggregation Pipeline Operators in the table below.

Stages operators:

Name Description

$project The $project function in MongoDB passes along the documents with only the
specified fields to the next stage in the pipeline. This may be the existing fields
from the input documents or newly computed fields.

$match The MongoDB $match operator filters the documents to pass only those
documents that match the specified condition(s) to the next pipeline stage.

$redact The $redact operator can change and gives a new form of each document in the
stream by restricting the content for each document based on information stored
in the documents themselves.

$unwind The MongoDB $unwind stages operator is used to deconstructs an array field
from the input documents to output a document for each element. Every output
document is the input document with the value of the array field replaced by the
element.

$group The MongoDB $group stages operator groups the documents by some specified
expression and groups the document for each distinct grouping. An _id field in
the output documents contains the distinct group by key. The output documents
can also contain computed fields that hold the values of some accumulator
expression grouped by the $group‘s _id field. This operator does not order its

18
SOC-II (MongoDB)

output documents.

$out The MongoDB $out write the resulting document of the aggregation pipeline to a
specified collection. The $out operator must be the last stage in the pipeline. The
$out operator lets the aggregation framework return result sets of any size.

Set operators:

Name Description

$setEquals The MongoDB $setEquals operators compares between two or more


arrays and returns true if they have the same distinct elements otherwise
it returns false.

$setIntersection The MongoDB $setIntersection operators takes two or more arrays and
returns a set of array with elements that appear in all of the input sets.

$setUnion The MongoDB $setUnion operators takes any number of argument


expressions or arrays and returns an array containing the elements that
appear in any input array.

$setDifference The MongoDB $setDifference operators takes exactly two argument


expressions i.e. two sets and returns an array containing the elements
that only exist in the first set; i.e. performs a relative complement of the
second set relative to the first.

$setIsSubset The MongoDB $setIsSubset operators takes exactly two argument


expressions i.e. two sets and returns true when the first array is a subset
of the second, including when the first array equals the second array,
and false otherwise.

$anyElementTrue The MongoDB $anyElementTrue operators takes a single argument


expression. i.e. a set and returns true if any elements of the set evaluate

19
SOC-II (MongoDB)

to true; otherwise, returns false. An empty array returns false.

$allElementsTrue The MongoDB $allElementsTrue operators takes a single argument


expression. i.e. a set and returns true if no element in the array is false.
Otherwise, returns false. An empty array returns true.

20
SOC-II (MongoDB)

EXPERIMENT-7

Aim: Get familiar with Database Commands in MongoDB.

Create New User - createUser Command

The createUser command is used to create a new user on the database where you run
the command. The createUser command returns an error message if the user already exists.A
database name must have to mention at the time to create a new user with createUser
action.A grantRole action must have to mention on a role’s database to grant the role to
another user. If you have the userAdmin or userAdminAnyDatabase role, or if you are
authenticated using the localhost exception, you have those actions.

Syntax:

{ createUser: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
Parameters:

Name Type Description

createUser string The name of the new user.

Pwd string The user’s password.

customData document Optional.

Roles array The roles granted to the user

writeConcern document Optional. The write concern briefs the guarantee that MongoDB
provides at the time of reporting on the success of a write

21
SOC-II (MongoDB)

operation. w: 1 as the default write concern.

Assume that our database name is userdetails and there are the following document:

db.userdetails.insert({"user_id" : "user1","password" :"1a2b3c" ,

"date_of_join" : "16/10/2010" ,"education" :"M.C.A." ,

"profession" : "CONSULTANT","interest" : "MUSIC",

"community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN


MUSIC"],

"community_moder_id" : ["MR. Alex","MR. Dang","MR Haris"],

"community_members" : [700,200,1500],

"friends_id" : ["kumar","harry","anand"],

"ban_friends_id" :["Amir","Raja","mont"]});

Example

The following createUser command creates a user myNewuser on the userdetails


database. The command gives myNewuser the clusterAdmin and readAnyDatabase roles on
the admin database and the readWrite role on the userdetails database:

db.getSiblingDB("userdetails").runCommand( { createUser: "myNewuser",

pwd: "thisPassword",

customData: { profession : "DOCTOR" },

roles: [

{ role: "clusterAdmin", db: "admin" },

{ role: "readAnyDatabase", db: "admin" },

"readWrite"

],

writeConcern: { interest : "SPORTS" }

})

22
SOC-II (MongoDB)

To see the User Information - usersInfo Command

The command usersInfo returns information about one or more users.

Syntax:

{ usersInfo: { user: <name>, db: <db> },


showCredentials: <Boolean>,
showPrivileges: <Boolean>
}
Parameters:

Name Type Description

usersInfo Various The user(s) about whom to return information.

showCredentials Boolean Optional. If the field set to true the user’s password hash will
be displayed, it is false by default.

showPrivileges Boolean Optional. If the field set to true to show the user’s full set of
privileges, including expanded information for the inherited
roles, it is false by default.

To Update the User Information - updateUser Command

The updateUser command updates the profile of the user on the specific database.
This command completely replaces the data of the previous field’s values. It is required to
specify the updateUser field and at least one other field, other than writeConcern to update a
user.

Syntax:

{ updateUser: "<username>",
pwd: "<cleartext password&glt;",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }

23
SOC-II (MongoDB)

}
Parameters:

Name Type Description

updateUser string The name of the user to update.

pwd string Optional. The user’s password.

customData document Optional. Any arbitrary information.

roles array Optional. The roles granted to the user. An update to the roles
array replace the values of the previous array.

writeConcern document Optional. The write concern briefs the guarantee that MongoDB
provides at the time of reporting on the success of a write
operation. w: 1 as the default write concern.

To Drop the User Information - dropUser Command

The dropUser command is used to remove the user from the concern database.

Syntax:

{
dropUser: "<user>",
writeConcern: { <write concern> }
}
Parameters:

Name Type Description

dropUser string The name of the user to delete. This command will work only
the database where the user exists.

24
SOC-II (MongoDB)

writeConcern document Optional. The write concern briefs the guarantee that MongoDB
provides at the time of reporting on the success of a write
operation. w: 1 as the default write concern. .

To Drop All the Users Information – dropAllUsersFromDatabase Command

This command removes all users from the concern database on which you run the command.

Syntax:

{
dropAllUsersFromDatabase: 1,
writeConcern: { <write concern> }
}
Parameters:

Name Type Description

dropAllUsersFromDatabase integer Specify 1 to drop all the users from the current
database.

writeConcern document Optional. The write concern briefs the guarantee


that MongoDB provides at the time of reporting
on the success of a write operation. w: 1 as the
default write concern.

Example

If we want to remove the user myNewuser1 from the userdetails database the following
sequence of operations in the mongo shell can be used.

> use userdetails;

switched to db userdetails

> db.runCommand( { dropAllUsersFromDatabase: 1, writeConcern: { w: "majority"


}});

25
SOC-II (MongoDB)

To Grants additional roles to a user - grantRolesToUser Command

This command grants additional roles to a user.

Syntax:

{ grantRolesToUser: "<user>",
roles: [ <roles> ],
writeConcern: { <write concern> }
}
Parameters:

Name Type Description

grantRolesToUser string The name of the user to give additional roles.

roles array An array of additional roles to grant to the user.

writeConcern document Optional. The write concern briefs the guarantee that
MongoDB provides at the time of reporting on the success
of a write operation. w: 1 as the default write concern.

To Revoke Roles From a User – revokeRolesFromUser

This command is used to remove a one or more roles from a user on the database where the
roles exist.

Syntax:

{ revokeRolesFromUser: "<user>",
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
Parameters:

26
SOC-II (MongoDB)

Name Type Description

revokeRolesFromUser string The user to remove roles from.

roles array The roles to revoke from the user.

writeConcern document Optional. The write concern briefs the guarantee that
MongoDB provides at the time of reporting on the
success of a write operation. w: 1 as the default write
concern.

27
SOC-II (MongoDB)

EXPERIMENT-8

Aim: Insert data into MongoDB database.

Insert data in MongoDB


we are going to discuss how to insert data into a collection. The documents stored in
MongoDB are JSON-like. All data stored in the collection are in BSON format.

Switch to a MongoDB database

Here, our database is "myinfo".

> use myinfo

switch to db myinfo

Define a document for MongoDB database

The following document can be stored in MongoDB.

> document=({"user_id" : "ABCDBWN","password" :"ABCDBWN" ,"date_of_join"


: "15/10/2010" ,"education" :"B.C.A." , "profession" : "DEVELOPER","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL
MUSIC","WESTERN MUSIC"],"community_moder_id" : ["MR. BBB","MR.
JJJ","MR MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id"
:["BAN123","BAN456","BAN789"]});

Defined document shows in command prompt

"user_id" : "ABCDBWN",

"password" : "ABCDBWN",

"date_of_join" : "15/10/2010",

"education" : "B.C.A.",

"profession" : "DEVELOPER",

"interest" : "MUSIC",

"community_name" : [

28
SOC-II (MongoDB)

"MODERN MUSIC",

"CLASSICAL MUSIC",

"WESTERN MUSIC"

],

"community_moder_id" : [

"MR. BBB",

"MR. JJJ",

"MR MMM"

],

"community_members" : [

500,

200,

1500

],

"friends_id" : [

"MMM123",

"NNN123",

"OOO123"

],

"ban_friends_id" : [

"BAN123",

"BAN456",

"BAN789"

29
SOC-II (MongoDB)

Insert a document into a collection

To save the above document into the collection "userdetails" under "myinfo" database the
following command can be used -

> db.userdetails.insert(document)

Write document using linebreak

Linebreaks can also be used while typing a document. This can be useful when writing a
lengthy document as shown bellow:

>document=({"user_id" : "ABCDBWN","password" :"ABCDBWN" ,"date_of_join" :


"15/10/2010" ,

"education" :"B.C.A." , "profession" : "DEVELOPER","interest" : "MUSIC",

"community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN


MUSIC"],

"community_moder_id" : ["MR. BBB","MR. JJJ","MR MMM"],

"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],

"ban_friends_id" :["BAN123","BAN456","BAN789"]});

Insert data into a collection without defining a document

Data can be inserted directly through the shell without defining the document -

>db.userdetails.insert({"user_id" : "xyz123","password" :"xyz123" ,"date_of_join" :


"15/08/2010" ,

"education" :"M.C.A." , "profession" : "Software consultant","interest" : "Film",

"community" : [

"name" : "DDD FILM CLUB",

"moder_id" : "MR. DBNA",

"members" : "25000",

},

30
SOC-II (MongoDB)

"name" : "AXN MOVIES",

"moder_id" : "DOGLUS HUNT",

"members" : "15000",

},

"name" : "UROPEAN FILM LOVERS",

"moder_id" : "AMANT LUIS",

"members" : "20000",

],

"friends" :[

"user_id" : "KKK258",

},

"user_id" : "LLL147",

},

"user_id" : "MMM369",

],

"ban_friends" :[

"user_id" : "BAN147"

31
SOC-II (MongoDB)

},

"user_id" : "BAN258"

},

"user_id" : "BAN369"

});

View the inserted data into the collection

>db.userdetails.find();

"user_id" : "xyz123",

"password" : "xyz123",

"date_of_join" : "15/08/2010",

"education" : "M.C.A.",

"profession" : "Software consultant",

"interest" : "Film",

"community" : [

"name" : "DDD FILM CLUB",

"moder_id" : "MR. DBNA",

"members" : "25000"

},

32
SOC-II (MongoDB)

"name" : "AXN MOVIES",

"moder_id" : "DOGLUS HUNT",

"members" : "15000"

},

"name" : "UROPEAN FILM LOVERS",

"moder_id" : "AMANT LUIS",

"members" : "20000"

],

"friends" : [

"user_id" : "KKK258"

},

"user_id" : "LLL147"

},

"user_id" : "MMM369"

],

"ban_friends" : [

"user_id" : "BAN147"

},

33
SOC-II (MongoDB)

"user_id" : "BAN258"

},

"user_id" : "BAN369"

34
SOC-II (MongoDB)

EXPERIMENT-9

Aim:Updation of data in MongoDB with Update() function.

Update data in MongoDB with update() function


The update can be done with update(). The update() takes four arguments - criteria,
objectnew, upsert and multi.

criteria - Query which specify the record to update;

objectnew- Specify the updated information or it can be used by $ operator (i.e. $inc...).

upsert - An upsert do update the record if match the criteria and insert a record if not match.

multi - This argument asks for updates all matching rows or just the first one(which is
default).

Our database name is 'myinfo' and our collection name is 'userdetails'. Here, inserting two
more records.

> document=({"user_id" : "MNOPBWN","password" :"MNOPBWN" ,"date_of_join" :


"16/10/2010" ,"education" :"M.C.A." , "profession" : "CONSULTANT","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN
MUSIC"],"community_moder_id" : ["MR. BBB","MR. JJJ","MR
MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id"
:["BAN123","BAN456","BAN789"]});

> db.userdetails.insert(document)

> document=({"user_id" : "QRSTBWN","password" :"QRSTBWN" ,"date_of_join" :


"17/10/2010" ,"education" :"M.B.A." , "profession" : "MARKETING","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN
MUSIC"],"community_moder_id" : ["MR. BBB","MR. JJJ","MR
MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id"
:["BAN123","BAN456","BAN789"]});

> db.userdetails.insert(document)

update() command

If we want to re-write the document into the collection 'userdetails' with a change of
'password' is 'NEWPASSWORD' where 'user_id' is 'QRSTBWN' the following update()
command can be written. If the criteria argument matches with any record the update will

35
SOC-II (MongoDB)

take place otherwise a new record will be inserted. The following example will update the
first matching criteria into the collection.

> db.userdetails.update({"user_id" : "QRSTBWN"},{"user_id" : "QRSTBWN","password"


:"NEWPASSWORD" ,"date_of_join" : "17/10/2010" ,"education" :"M.B.A." , "profession" :
"MARKETING","interest" : "MUSIC","community_name" :["MODERN MUSIC",
"CLASSICAL MUSIC","WESTERN MUSIC"],"community_moder_id" : ["MR.
BBB","MR. JJJ","MR MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id"
:["BAN123","BAN456","BAN789"]});

View the updated data into the collection

>db.userdetails.find().pretty();

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

"user_id" : "MNOPBWN",

"password" : "MNOPBWN",

"date_of_join" : "16/10/2010",

"education" : "M.C.A.",

"profession" : "CONSULTANT",

"interest" : "MUSIC",

"community_name" : [

"MODERN MUSIC",

"CLASSICAL MUSIC",

"WESTERN MUSIC"

],

"community_moder_id" : [

"MR. BBB",

"MR. JJJ",

36
SOC-II (MongoDB)

"MR MMM"

],

"community_members" : [

500,

200,

1500

],

"friends_id" : [

"MMM123",

"NNN123",

"OOO123"

],

"ban_friends_id" : [

"BAN123",

"BAN456",

"BAN789"

"user_id" : "QRSTBWN",

"password" : "NEWPASSWORD",

"date_of_join" : "17/10/2010",

"education" : "M.B.A.",

"profession" : "MARKETING",

"interest" : "MUSIC",

37
SOC-II (MongoDB)

"community_name" : [

"MODERN MUSIC",

"CLASSICAL MUSIC",

"WESTERN MUSIC"

],

"community_moder_id" : [

"MR. BBB",

"MR. JJJ",

"MR MMM"

],

"community_members" : [

500,

200,

1500

],

"friends_id" : [

"MMM123",

"NNN123",

"OOO123"

],

"ban_friends_id" : [

"BAN123",

"BAN456",

"BAN789"

]}

38
SOC-II (MongoDB)

EXPERIMENT-10

Aim: Remove document from collection in MongoDB with remove()


Remove document from collection in MongoDB with remove()
we are going to discuss how to remove the document and entire collection. remove()
is used to remove a document and a collection. It may be a good practice if you execute a
find() before removing a document as you can fix criteria for removing the document.

Our database name is 'myinfo' and our collection name is 'userdetails'. Here, inserting
one more record.

> document=({"user_id" : "testuser","password" :"testpassword" ,"date_of_join" :


"16/10/2010" ,"education" :"M.C.A." , "profession" : "CONSULTANT","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN
MUSIC"],"community_moder_id" : ["MR. BBB","MR. JJJ","MR
MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id"
:["BAN123","BAN456","BAN789"]});

> db.userdetails.insert(document)

View the inserted data into the collection

>db.userdetails.find().pretty();
N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.
{
"user_id" : "MNOPBWN",
"password" : "MNOPBWN",
"date_of_join" : "16/10/2010",
"education" : "M.C.A.",
"profession" : "CONSULTANT",
"interest" : "MUSIC",
"community_name" : [
"MODERN MUSIC",
"CLASSICAL MUSIC",
"WESTERN MUSIC"
],
"community_moder_id" : [
"MR. BBB",
"MR. JJJ",
"MR MMM"
],
"community_members" : [

39
SOC-II (MongoDB)

500,
200,
1500
],
"friends_id" : [
"MMM123",
"NNN123",
"OOO123"
],
"ban_friends_id" : [
"BAN123",
"BAN456",
"BAN789"
]
}
{
"user_id" : "QRSTBWN",
"password" : "NEWPASSWORD",
"date_of_join" : "17/10/2010",
"education" : "M.B.A.",
"profession" : "MARKETING",
"interest" : "MUSIC",
"community_name" : [
"MODERN MUSIC",
"CLASSICAL MUSIC",
"WESTERN MUSIC"
],
"community_moder_id" : [
"MR. BBB",
"MR. JJJ",
"MR MMM"
],
"community_members" : [
500,
200,
1500
],
"friends_id" : [
"MMM123",
"NNN123",
"OOO123"
],
"ban_friends_id" : [
"BAN123",

40
SOC-II (MongoDB)

"BAN456",
"BAN789"
]
}
{
"user_id" : "testuser",
"password" : "testpassword",
"date_of_join" : "16/10/2010",
"education" : "M.C.A.",
"profession" : "CONSULTANT",
"interest" : "MUSIC",
"community_name" : [
"MODERN MUSIC",
"CLASSICAL MUSIC",
"WESTERN MUSIC"
],
"community_moder_id" : [
"MR. BBB",
"MR. JJJ",
"MR MMM"
],
"community_members" : [
500,
200,
1500
],
"friends_id" : [
"MMM123",
"NNN123",
"OOO123"
],
"ban_friends_id" : [
"BAN123",
"BAN456",
"BAN789"
]
}

Remove document with remove()

If we want to remove the document from the collection 'userdetails' which contains
the userid "testuser" the following mongodb command can be used :

>db.userdetails.remove( { "user_id" : "testuser" } )

41
SOC-II (MongoDB)

Remove all data from a collection

If we want to remove all data from the collection 'userdetails' the following mongodb
command can be used :

>db.userdetails.remove({})

Remove a collection using drop()

If we want to remove the entire 'userdetails' collection, including all of its documents the
following mongodb command can be used :

>db.userdetails.drop()

Output:

> db.userdetails.drop();
true
The drop() returns either true or false. The above function returns true, it means that the
operation has completed successfully.

Remove an entire Database using dropDatabase()

If we want to remove an entire database the following mongodb command can be used:

>db.dropDatabase()

It should be a good habit if you use the db command in mongodb prompt to know which
database is currently working and you can be sure before removing the database.

> db

myinfo

>db.dropDatabase();

{ "dropped" : "myinfo", "ok" : 1 }

42
SOC-II (MongoDB)

EXPERIMENT-11

Aim: Get Familiar with MongoDB Shell methods.

Mongodb Shell methods

Collection

Methods are below in the table

Name Description

db.collection.aggregate() Provides access to the aggregation pipeline.

db.collection.count() Wraps count to return a count of the number of


documents in a collection or matching a query.

db.collection.createIndex() Builds an index on a collection.

db.collection.dataSize() Returns the size of the collection. Wraps the size field
in the output of the collStats.

db.collection.distinct() Returns an array of documents that have distinct


values for the specified field.

db.collection.drop() Removes the specified collection from the database.

db.collection.dropIndex() Removes a specified index on a collection.

db.collection.dropIndexes() Removes all indexes on a collection

db.collection.explain() Returns information on the query execution of


various methods.

43
SOC-II (MongoDB)

db.collection.find() Performs a query on a collection and returns a cursor


object.

db.collection.findAndModify() Atomically modifies and returns a single document.

db.collection.findOne() Performs a query and returns a single document.

db.collection.getIndexes() Returns an array of documents that describe the


existing indexes on a collection.

db.collection.getShardDistribution() For collections in sharded clusters,


db.collection.getShardDistribution() reports data of
chunk distribution.

db.collection.getShardVersion() Internal diagnostic method for shard cluster.

db.collection.group() Provides simple data aggregation function. Groups


documents in a collection by a key, and processes the
results. Use aggregate() for more complex data
aggregation.

db.collection.insert() Creates a new document in a collection.

db.collection.isCapped() Reports if a collection is a capped collection.

db.collection.mapReduce() Performs map-reduce style data aggregation.

db.collection.reIndex() Rebuilds all existing indexes on a collection.

db.collection.remove() Deletes documents from a collection.

44
SOC-II (MongoDB)

db.collection.renameCollection() Changes the name of a collection.

db.collection.save() Provides a wrapper around an insert() and update() to


insert new documents.

db.collection.stats() Reports on the state of a collection. Provides a


wrapper around the collStats.

db.collection.storageSize() Reports the total size used by the collection in bytes.


Provides a wrapper around the storageSize field of
the collStats output.

db.collection.totalSize() Reports the total size of a collection, including the


size of all documents and all indexes on a collection.

db.collection.totalIndexSize() Reports the total size used by the indexes on a


collection. Provides a wrapper around the
totalIndexSize field of the collStats output.

db.collection.update() Modifies a document in a collection.

db.collection.validate() Performs diagnostic operations on a collection.

User Management

Name Description

db.auth() Authenticates a user to a database.

db.createUser() Creates a new user.

45
SOC-II (MongoDB)

db.updateUser() Updates user data.

db.changeUserPassword() Changes an existing user’s password.

db.dropAllUsers() Deletes all users associated with a database.

db.dropUser() Removes a single user.

db.grantRolesToUser() Grants a role and its privileges to a user.

db.revokeRolesFromUser() Removes a role from a user.

db.getUser() Returns information about the specified user.

db.getUsers() Returns information about all users associated with a database.

46
SOC-II (MongoDB)

EXPERIMENT-12

Aim: Perform various QUERIES on MongoDB.

Fetch documents from collection in MongoDB


Our database name is 'myinfo' and our collection name is 'userdetails'. Here, inserting
one more record.

>db.userdetails.insert({"user_id" : "user1","password" :"1a2b3c" ,"date_of_join" :


"16/10/2010" ,"education" :"M.C.A." , "profession" : "CONSULTANT","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN
MUSIC"],"community_moder_id" : ["MR. Alex","MR. Dang","MR
Haris"],"community_members" : [700,200,1500],"friends_id" :
["kumar","harry","anand"],"ban_friends_id" :["Amir","Raja","mont"]});

> db.userdetails.insert({"user_id" : "user2","password" :"11aa1a" ,"date_of_join" :


"17/10/2009" ,"education" :"M.B.A." , "profession" : "MARKETING","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN
MUSIC"],"community_moder_id" : ["MR. Roy","MR. Das","MR
Doglus"],"community_members" : [500,300,1400],"friends_id" :
["pal","viki","john"],"ban_friends_id" :["jalan","monoj","evan"]});

> db.userdetails.insert({"user_id" : "user3","password" :"b1c1d1" ,"date_of_join" :


"16/10/2010" ,"education" :"M.C.A." , "profession" : "IT COR.","interest" :
"ART","community_name" :["MODERN ART", "CLASSICAL ART","WESTERN
ART"],"community_moder_id" : ["MR. Rifel","MR. Sarma","MR
Bhatia"],"community_members" : [5000,2000,1500],"friends_id" :
["philip","anant","alan"],"ban_friends_id" :["Amir","Raja","mont"]});

> db.userdetails.insert({"user_id" : "user4","password" :"abczyx" ,"date_of_join" :


"17/8/2009" ,"education" :"M.B.B.S." , "profession" : "DOCTOR","interest" :
"SPORTS","community_name" :["ATHELATIC", "GAMES FAN GYES","FAVOURIT
GAMES"],"community_moder_id" : ["MR. Paul","MR. Das","MR
Doglus"],"community_members" : [2500,2200,3500],"friends_id" :
["vinod","viki","john"],"ban_friends_id" :["jalan","monoj","evan"]});

Fetch all data from the collection

If we want to fetch all documents from the collection the following mongodb command can
be used :

>db.userdetails.find();

or

>db.userdetails.find().pretty();
47
SOC-II (MongoDB)

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

Fetch documents from collection based on a criteria

If we want to fetch all documents from the collection 'userdetails' which hold the educational
qualification "M.C.A.", the following mongodb command can be used

> db.userdetails.find({"education":"M.C.A."}).pretty();

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

Fetch documents from collection with selective fields


Our database name is 'myinfo' and our collection name is 'userdetails'. Here, is the
collection bellow.

Sample collection "userdetails"

"_id" : ObjectId("528cab88e1e41035b889f2bf"),

"user_id" : "user1",

"password" : "1a2b3c",

"date_of_join" : "16/10/2010",

"education" : "M.C.A.",

"profession" : "CONSULTANT",

"interest" : "MUSIC",

"community_name" : [

"MODERN MUSIC",

"CLASSICAL MUSIC",

"WESTERN MUSIC"

],

"community_moder_id" : [

48
SOC-II (MongoDB)

"MR. Alex",

"MR. Dang",

"MR Haris"

],

"community_members" : [

700,

200,

1500

],

"friends_id" : [

"kumar",

"harry",

"anand"

],

"ban_friends_id" : [

"Amir",

"Raja",

"mont"

Fetch selective field from collection based on a criteria

If we want to fetch only the "user_id" for all documents from the collection 'userdetails'
which hold the educational qualification "M.C.A.", the following mongodb command can be
used :

>db.userdetails.find({"education":"M.C.A."},{"user_id" : 1}).pretty();

49
SOC-II (MongoDB)

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

Fetch more than one fields from collection based on a criteria

If we want to fetch the "user_id" , "password" and "date_of_jon" for all documents
from the collection 'userdetails' which hold the educational qualification "M.C.A.", the
following mongodb command can be used :

>db.userdetails.find({"education":"M.C.A."},{"user_id" :
1,"password":1,"date_of_join":1}).pretty();
N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

The above output shows that two documents have fetched from the collection "userdetails"
but only the data of user_id, password and date_of_join have appeared for those documents
who have the qualification "M.C.A.".

Fetch all data except selective field from collection based on a criteria

If we want to fetch all data except the "user_id" field for all documents from the collection
'userdetails' which hold the educational qualification "M.C.A.", the following mongodb
command can be used :

>db.userdetails.find({"education":"M.C.A."},{"user_id" : 0}).pretty();

N.B. find() method displays the documents in a non structured format but to display the
results in a formatted way, the pretty() method can be used.

MongoDB sort results from collection


Syntax:

collection.find().sort( {column1:1or -1 [, column2:1 or -1] });


Parameters:

Arguments Description

collection Name of the collection.

column1, column2 Name of the fields or columns.

50
SOC-II (MongoDB)

1 or -1 indicates the order (1 for ascending and -1 for descending)

MongoDB skip() and limit()


The limit() function in MongoDB is used to specify the maximum number of results to be
returned. Only one parameter is required for this function.to return the number of the desired
result.

Sometimes it is required to return a certain number of results after a certain number of


documents. The skip() can do this job.

MongoDB query language


mongo query language can be used with sort() and can be implemented like WHERE clause
of SQL.

The MongoDB server treats all the query parameters as a single object. Some object such as
$query, $orderby etc can be used to get the same result as return simple mongo query
language. The $query can be evaluated as the WHERE clause of SQL and $orderby sorts the
results as specified order.

MongoDB $in and $or operation in query


$in, and $or can be used with mongodb queries.

The $in operator checks a value within the specified values within the arguments.

The $or operator checks whether any of the specified value is matching in the documents.

MongoDB query with null


null value in mongodb documents can be fetched using $type, $exists operators.

The $type operator in mongodb matches values based on their BSON type.

The $exist operator checks whether the particular field exist or not.

MongoDB Dot notation


the usage of Dot notation in JSON style object in MongoDB database.

In MongoDB the JSON-style of objects can be store. The MongoDB database can understand
the structure of these objects and can evaluate the various type of queries from the collection
of this database.

51

You might also like