Lecture - 1 MongoDB
Lecture - 1 MongoDB
MongoDB
What is a Database?
An organized collection of data.
A method to manipulate and access the data.
Unorganized
Organized
Introduction To MongoDB
3) MongoDB Atlas :
MongoDB Atlas is a global cloud database service. It is a database as a service that
allows
you to focus on building apps rather than spending time managing the databases.
MongoDB Structure
• MongoDB stores data in collections and documents.
• A collection is a group of MongoDB documents
• A document is a set of key-value pairs.
Collection : A container for documents (like a table).
Document : A JSON-like record within a collection (like a row).
Field : A key-value pair within a document (like a column).
MongoDB Basics
• Data formats
In MongoDB, you will often deal with JSON and BSON formats. Therefore, it’s important to fully understand
them.
• JSON
JSON stands for JavaScript Object Notation. JSON syntax is based on a subset of JavaScript ECMA-262 3rd
edition.
A JSON document is a collection of fields and values in a structured format. For example:
{
"first_name": "John",
"last_name": "Doe",
"age": 22,
"skills": ["Programming","Databases", "API"]
}
MongoDB Basics
• BSON
BSON stands for Binary JSON, which is a binary-coded
serialization of JSON-
like documents.
• Documents
MongoDB stores data records as BSON documents, which are
simply called
documents.
MongoDB Basics
{
title: "MongoDB Basics",
published_date: new Date('Jan 01, 2021'),
isbn": "978-4-7766-7944-8"
MongoDB Basics
Note that the second document has one more field than the first
one. In theory, you can have completely different fields for every
document.
A database can be referenced by a name for example bookdb. The database names
cannot:
• Be an empty string ("").
• Contain any of these characters: /, \, ., “, *, <, >, :, |, ?, $, (a single space), or \0
(the null character).
• Exceed the maximum size which is 64 bytes.
MongoDB also has some reserved database names such as admin, local, and config
that you cannot use to create new databases.
Namespace
• The mongo shell allows you to enter multiline commands. It will detect if the JavaScript statement is
complete when you press enter.
• If the statement is not complete, the mongo shell will allow you to type on the next line after the three
dots (...).
function add(a, b) {
... return a + b;
... }
add(10,20);
30
To clear the screen, you use the console.clear() like this: console.clear()
• Database
o Creating, connect, listing, droping
• CRUD
o Create - New collection
Inserting data
o Read - How to read data
o Update data
o Delete data
Database And Collection
• Now, you can access the books collection from the bookstore database via
the db variable like this:
> db.books
bookstore.books
Basic CRUD Operations
The following section shows you how to create (C), read (R),
update (U), and delete (D) a document. These operations are
often referred to as CRUD operations.
CREATE READ
insertOne() find()
insertMany() findOne()
UPDATE DELETE
updateOne() deleteOne()
updateMany() deleteMany()
Create
• To add a document to a collection, you use the insertOne() method of the
collection.
The following command adds a new document (or a new book) to the books
collection:
db.books.insertOne({
title: "MongoDB Tutorial",
published_year: 2020
})
Output :
{
"acknowledged" : true,
"insertedId" : ObjectId("5f2f39fb82f5c7bd6c9375a8")
}
Create
• Once you press enter, the mongo shell sends the command to the MongoDB
server.
• If the command is valid, MongoDB inserts the document and returns the result.
In this case, it returns an object that has two keys acknowledged and insertedId.
• The value of the insertedId is the value of the _id field in the document.
• When you add a document to a collection without specifying the _id field,
MongoDB automatically assigns a unique ObjectId value to the _id field and add
it to the document.
• MongoDB uses the _id field to uniquely identify the document in the collection.
Read
To select documents in a collection, you use the findOne()
method:
db.books.findOne()
Output :
{
_id: ObjectId("62143f34cca1c7af0ad1d126"),
title: 'MongoDB Tutorial',
published_year: 2020
}
Update
1) Null : The null type is used to represent a null and a field that does not exist. For example
{
"isbn": null
2) Boolean : The boolean type has two values true and false. For example:
"best_seller": true
3) Number : By default, the mongo shell uses the 64-bit floating-point numbers. For example:
"price": 9.95,
“pages": 851
}
MongoDB Data Types
The NumberInt and NumberLong classes represent 4-byte and 8-byte integers respectively. For example:
{
"year": NumberInt("2020"),
"words": NumberLong("95403")
}
4) String : The string type represents any string of UTF-8 characters. For example:
{
"title": "MongDB Data Types"
}
5) Date : The date type stores dates as 64-bit integers that represents milliseconds since the Unix epoch
(January 1, 1970). It does not store the time zone. For example:
{
"updated_at": new Date()
MongoDB Data Types
6) Regular Expression : MongoDB allows you to store JavaScript regular expressions. For example:
"pattern": /\d+/
In this example, /\d+/ is a regular expression that matches one or more digits.
7) Array : The array type allows you to store a list of values of any type. The values do not have to be in the
same type, for example:
The good thing about arrays in the document is that MongoDB understands their structures and allows you to
carry operations on their elements.
For example, you can query all documents where 5 is an element of the reviews array. Also, you can create an
index on the reviews array to improve the query performance.
MongoDB Data Types
8) Embeded Document : A value of a document can be another document that is often referred to as an
embedded document.
The following example shows a book document that contains the author document as an embedded
document:
{
"title": "MongoDB Tutorial",
"pages": 945,
"author": {
"first_name": "John",
"last_name": "Doe"
}
}
In this example, the author document has its own key/value pairs including first_name and last_name.