0% found this document useful (0 votes)
34 views24 pages

Module - 6

The document discusses key concepts in MongoDB including databases, collections, and documents which are used to store and organize data, with databases containing collections and collections containing documents made up of key-value pairs; it also provides examples of creating databases and collections as well as inserting, querying, updating, and deleting documents. Common CRUD operations in MongoDB like insert, find, update, and delete are demonstrated through examples interacting with a sample student database and collection.

Uploaded by

patricknamdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views24 pages

Module - 6

The document discusses key concepts in MongoDB including databases, collections, and documents which are used to store and organize data, with databases containing collections and collections containing documents made up of key-value pairs; it also provides examples of creating databases and collections as well as inserting, querying, updating, and deleting documents. Common CRUD operations in MongoDB like insert, find, update, and delete are demonstrated through examples interacting with a sample student database and collection.

Uploaded by

patricknamdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

Module - 6

MongoDB – Database, Collection, and Document

Databases, collections, documents are important parts of MongoDB without


them you are not able to store data on the MongoDB server. A Database
contains a collection, and a collection contains documents and the
documents contain data, they are related to each other.

Database

View Database:

To see how many databases are present in your MongoDB server, write the
following statement in the mongo shell:
show dbs
For Example:
Here, we freshly started MongoDB so we do not have a database except
these three default databases, i.e, admin, config, and local.

Creating Database:

In the mongo shell, you can create a database with the help of the
following command:
use database_name
This command actually switches you to the new database if the given name
does not exist and if the given name exists, then it will switch you to the
existing database. Now at this stage, if you use the show command to see
the database list where you will find that your new database is not present
in that database list because, in MongoDB, the database is actually created
when you start entering data in that database.
For Example:
Here, we create a new database named GeeksforGeeks using the use
command. After creating a database when we check the database list we
do not find our database on that list because we do not enter any data in
the GeeksforGeeks database.
Collection
Collections are just like tables in relational databases, they also store data,
but in the form of documents. A single database is allowed to store multiple
collections.

Schemaless:

As we know that MongoDB databases are schemaless. So, it is not


necessary in a collection that the schema of one document is similar to
another document. Or in other words, a single collection contains different
types of documents like as shown in the below example where
mystudentData collection contain two different types of documents:
Creating collection:

After creating database now we create a collection to store documents. The


collection is created using the following syntax:
db.collection_name.insertOne({..})
Here, insertOne() function is used to store single data in the specified
collection. And in the curly braces {} we store our data or in other words, it
is a document.
For Example:
In this example, we create a collection named as the Author and we insert
data in it with the help of insertOne() function. Or in other words, {name:
“Ankita”} is a document in the Author collection, and in this document, the
name is the key or field and “Ankita” is the value of this key or field. After
pressing enter we got a message(as shown in the above image) and this
message tells us that the data enters successfully (i.e., “acknowledge”:
true) and also assigns us an automatically created id. It is the special
feature provided by MongoDB that every document provided a unique id
and generally, this id is created automatically, but you are allowed to
create your own id (must be unique).
Document
In MongoDB, the data records are stored as BSON documents. Here, BSON
stands for binary representation of JSON documents, although BSON
contains more data types as compared to JSON. The document is created
using field-value pairs or key-value pairs and the value of the field can be
of any BSON type.
Syntax:
{
field1: value1
field2: value2
....
fieldN: valueN
}

Naming restriction of fields:

Before moving further first you should learn about the naming restrictions
for fields:
• The field names are of strings.
• The _id field name is reserved to use as a primary key. And the value
of this field must be unique, immutable, and can be of any type other
than an array.
• The field name cannot contain null characters.
• The top-level field names should not start with a dollar sign ($).
Document Size: The maximum size of the BSON document is 16MB. It
ensures that the single document does not use too much amount of RAM or
bandwidth(during transmission). If a document contains more data than
the specified size, then MongoDB provides a GridFS API to store such type
of documents.
Important Notes –
• A single document may contain duplicate fields.
• MongoDB always saves the order of the fields in the documents
except for the _id field (which always comes in the first place) and
the renaming of fields may change the order of the fields in the
documents.
• _id Field: In MongoDB, every document store in the collection must
contain a unique _id field it is just like a primary key in a relational
database. The value of the _id field can be set by the user or by the
system (if the user does not create an _id field, then the system will
automatically generate an ObjectId for _id field).
o When you create a collection MongoDB automatically creates a
unique index on the _id field.
o The _id field is the first field of every document.
o The value of the _id field can be of any BSON type except
arrays.
o The default value of the _id field is ObjectId.
Example #1:
Here, name, branch, course, and paid field contain values of string type.
amount field contains the value of integer type and _id field is generated by
the system.
Example #2:

Here, the _id field is created by the user.

MongoDB CRUD operations


MongoDB provides a set of some basic but most essential operations that will help you to
easily interact with the MongoDB server and these operations are known as CRUD
operations.
Create Operations –
The create or insert operations are used to insert or add new documents in the collection. If a
collection does not exist, then it will create a new collection in the database. You can perform,
create operations using the following methods provided by the MongoDB:

Method Description

db.collection.insertOne() It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the collection.

db.createCollection() It is used to create an empty collection.

Example 1: In this example, we are inserting details of a single student in the form of
document in the student collection using db.collection.insertOne() method.
Example 2: In this example, we are inserting details of the multiple students in the form of
documents in the student collection using db.collection.insertMany() method.
Read Operations –
The Read operations are used to retrieve documents from the collection, or in other words,
read operations are used to query a collection for a document. You can perform read
operation using the following method provided by the MongoDB:

Method Description

db.collection.find() It is used to retrieve documents from the collection.

.pretty() : this method is used to decorate the result such that it is easy to read.
Example : In this example, we are retrieving the details of students from the student collection
using db.collection.find() method.
Update Operations –
The update operations are used to update or modify the existing document in the collection.
You can perform update operations using the following methods provided by the MongoDB:

Method Description

It is used to update a single document in the collection


db.collection.updateOne() that satisfy the given criteria.

It is used to update multiple documents in the collection


db.collection.updateMany() that satisfy the given criteria.

It is used to replace single document in the collection


db.collection.replaceOne() that satisfy the given criteria.
Example 1: In this example, we are updating the age of Sumit in the student collection using
db.collection.updateOne() method.
Example 2: In this example, we are updating the year of course in all the documents in the
student collection using db.collection.updateMany() method.
Delete Operations –
The delete operation are used to delete or remove the documents from a collection. You can
perform delete operations using the following methods provided by the MongoDB:

Method Description

It is used to delete a single document from the collection


db.collection.deleteOne() that satisfy the given criteria.

It is used to delete multiple documents from the


db.collection.deleteMany() collection that satisfy the given criteria.

Example 1: In this example, we are deleting a document from the student collection using
db.collection.deleteOne() method.
Example 2: In this example, we are deleting all the documents from the student collection
using db.collection.deleteMany() method.
Redis - Data Types
Strings
Redis string is a sequence of bytes. Strings in Redis are binary safe,
meaning they have a known length not determined by any special
terminating characters. Thus, you can store anything up to 512
megabytes in one string.

Example
redis 127.0.0.1:6379> SET name "tutorialspoint"
OK
redis 127.0.0.1:6379> GET name
"tutorialspoint"
In the above example, SET and GET are Redis commands, name is
the key used in Redis and tutorialspoint is the string value that is
stored in Redis.

Hashes
A Redis hash is a collection of key value pairs. Redis Hashes are
maps between string fields and string values. Hence, they are used
to represent objects.

Example
redis 127.0.0.1:6379> HMSET user:1 username tutorialspoint
password
tutorialspoint points 200
OK
redis 127.0.0.1:6379> HGETALL user:1
1) "username"
2) "tutorialspoint"
3) "password"
4) "tutorialspoint"
5) "points"
6) "200"

In the above example, hash data type is used to store the user's
object which contains basic information of the user. Here HMSET,
HGETALL are commands for Redis, while user:1 is the key.

Lists:
Redis lists are linked lists of string values. Redis lists are frequently
used to:

• Implement stacks and queues.


• Build queue management for background worker systems.

Basic commands
• LPUSH adds a new element to the head of a list; RPUSH adds to the
tail.
• LPOP removes and returns an element from the head of a
list; RPOP does the same but from the tails of a list.
• LLEN returns the length of a list.
• LMOVE atomically moves elements from one list to another.

Examples

1) Treat a list like a queue (first in, first out):

> LPUSH bikes:repairs bike:1


(integer) 1

> LPUSH bikes:repairs bike:2

(integer) 2

> RPOP bikes:repairs

"bike:1"

> RPOP bikes:repairs

"bike:2"

2)Treat a list like a stack (first in, last out):

> LPUSH bikes:repairs bike:1


(integer) 1
> LPUSH bikes:repairs bike:2
(integer) 2
> LPOP bikes:repairs
"bike:2"
> LPOP bikes:repairs
"bike:1"
Redis sets
Redis Sets are an unordered collection of strings. In Redis, you can
add, remove, and test for the existence of members.

Basic commands
• SADD adds a new member to a set.

• SREM removes the specified member from the set.

• SISMEMBER tests a string for set membership.

• SINTER returns the set of members that two or more sets have in common
(i.e., the intersection).
• SCARD returns the size (a.k.a. cardinality) of a set.

Examples

Store the sets of bikes racing in France and the USA. Note that if
you add a member that already exists, it will be ignored.

1)

> SADD bikes:racing:france bike:1


(integer) 1
> SADD bikes:racing:france bike:1
(integer) 0
> SADD bikes:racing:france bike:2 bike:3
(integer) 2
> SADD bikes:racing:usa bike:1 bike:4
(integer) 2
2) Check whether bike:1 or bike:2 are racing in the US.

> SISMEMBER bikes:racing:usa bike:1


(integer) 1
> SISMEMBER bikes:racing:usa bike:2
(integer) 0

)
3 Which bikes are common in both races?

SINTER bikes:racing:france bikes:racing:usa


1) "bike:1"
4) How many bikes are racing in France?
> SCARD bikes:racing:france
(integer) 3
SortedSet
A Redis sorted set is a collection of unique strings (members) ordered by an
associated score. When more than one string has the same score, the strings
are ordered lexicographically.

Let's start with a simple example, we'll add all our racers and the
score they got in the first race:

> ZADD racer_scores 10 "Norem"


(integer) 1
> ZADD racer_scores 12 "Castilla"
(integer) 1
> ZADD racer_scores 8 "Sam-Bodden" 10 "Royce" 6 "Ford" 14
"Prickett"
(integer) 4

Note that the ZRANGE order is low to high, while the ZREVRANGE order is high
to low:

> ZRANGE racer_scores 0 -1


1) "Ford"
2) "Sam-Bodden"
3) "Norem"
4) "Royce"
5) "Castilla"
6) "Prickett"
> ZREVRANGE racer_scores 0 -1
1) "Prickett"
2) "Castilla"
3) "Royce"
4) "Norem"
5) "Sam-Bodden"
6) "Ford"

It is possible to return scores as well, using the WITHSCORES argument:

> ZRANGE racer_scores 0 -1 withscores


1) "Ford"
2) "6"
3) "Sam-Bodden"
4) "8"
5) "Norem"
6) "10"
7) "Royce"
8) "10"
9) "Castilla"
10) "12"
11) "Prickett"
12) "14"

You might also like