Soc-Ii Mongodb Record
Soc-Ii Mongodb Record
EXPERIMENT-1
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:
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.
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
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.
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
Pre-built binary packages of MongoDB are available for both 32 bit and 64 bit. You
can download it, and install.
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.
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)
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.
5
SOC-II (MongoDB)
EXPERIMENT-3
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++;
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>
1 use mytest
2 db.getSiblingDB('sampleDB').getCollectionNames();
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'.
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:
10 test@myhost>
11
13
7
SOC-II (MongoDB)
3;
4 ... }
8
SOC-II (MongoDB)
EXPERIMENT-4
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.
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
integer Digits.
10
SOC-II (MongoDB)
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:
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}
12
SOC-II (MongoDB)
EXPERIMENT-5
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.
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.
Name Description
Name Description
$mod Performs a modulo operation on the value of a field and selects documents with a
specified result.
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.
Projection operator
Name Description
$elemMatch(projection) Projects the first element in an array that matches the specified
$elemMatch condition.
Syntax:
Name Description
15
SOC-II (MongoDB)
Our database name is 'myinfo' and our collection name is "items". Here, is the
collection bellow.
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)
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:
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.
> 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.
{
"_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
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
$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.
19
SOC-II (MongoDB)
20
SOC-II (MongoDB)
EXPERIMENT-7
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:
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)
Assume that our database name is userdetails and there are the following document:
"community_members" : [700,200,1500],
"friends_id" : ["kumar","harry","anand"],
"ban_friends_id" :["Amir","Raja","mont"]});
Example
pwd: "thisPassword",
roles: [
"readWrite"
],
})
22
SOC-II (MongoDB)
Syntax:
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.
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:
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.
The dropUser command is used to remove the user from the concern database.
Syntax:
{
dropUser: "<user>",
writeConcern: { <write concern> }
}
Parameters:
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. .
This command removes all users from the concern database on which you run the command.
Syntax:
{
dropAllUsersFromDatabase: 1,
writeConcern: { <write concern> }
}
Parameters:
dropAllUsersFromDatabase integer Specify 1 to drop all the users from the current
database.
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.
switched to db userdetails
25
SOC-II (MongoDB)
Syntax:
{ grantRolesToUser: "<user>",
roles: [ <roles> ],
writeConcern: { <write concern> }
}
Parameters:
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.
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)
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
switch to db myinfo
"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)
To save the above document into the collection "userdetails" under "myinfo" database the
following command can be used -
> db.userdetails.insert(document)
Linebreaks can also be used while typing a document. This can be useful when writing a
lengthy document as shown bellow:
"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],
"ban_friends_id" :["BAN123","BAN456","BAN789"]});
Data can be inserted directly through the shell without defining the document -
"community" : [
"members" : "25000",
},
30
SOC-II (MongoDB)
"members" : "15000",
},
"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"
});
>db.userdetails.find();
"user_id" : "xyz123",
"password" : "xyz123",
"date_of_join" : "15/08/2010",
"education" : "M.C.A.",
"interest" : "Film",
"community" : [
"members" : "25000"
},
32
SOC-II (MongoDB)
"members" : "15000"
},
"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
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.
> db.userdetails.insert(document)
> 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.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
Our database name is 'myinfo' and our collection name is 'userdetails'. Here, inserting
one more record.
> db.userdetails.insert(document)
>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"
]
}
If we want to remove the document from the collection 'userdetails' which contains
the userid "testuser" the following mongodb command can be used :
41
SOC-II (MongoDB)
If we want to remove all data from the collection 'userdetails' the following mongodb
command can be used :
>db.userdetails.remove({})
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.
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();
42
SOC-II (MongoDB)
EXPERIMENT-11
Collection
Name Description
db.collection.dataSize() Returns the size of the collection. Wraps the size field
in the output of the collStats.
43
SOC-II (MongoDB)
44
SOC-II (MongoDB)
User Management
Name Description
45
SOC-II (MongoDB)
46
SOC-II (MongoDB)
EXPERIMENT-12
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.
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.
"_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"
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.
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.
Arguments Description
50
SOC-II (MongoDB)
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.
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.
The $type operator in mongodb matches values based on their BSON type.
The $exist operator checks whether the particular field exist or not.
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