Mongodb Notes HD Excl
Mongodb Notes HD Excl
Mongo DB
INTRODUCTION TO MONGO
SQL vs NOSQL
MongoDB terminologies
JSON vs BSON
INSTALLATION
CRUD OPERATIONS
Insert Operation
Search Operations
Update Operations
Updating arrays and embedded Documents
Deletion Operations
Importing JSON in MongoDB
Mongo export
Comparison Operators
Cursors
Cursor methods
Logical Operators
Complex Expressions
Elements Operators
Projections
Embedded Documents
Indexes
Aggregation
MongoDB atlas
MongoDB Compass
MongoDB Drivers
Python
INTRODUCTION TO MONGO
MongoDB is a document database. It stores data in a type of JSON format
called BSON. Created by company called 10gen which is now known as
MongoDB, founded by Eliot Horowitz and Merriman in 2007
Mongo DB 1
A record in MongoDB is a document, which is a data structure composed of key
value pairs similar to the structure of JSON objects
{
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
}
SQL vs NOSQL
SQL NOSQL
Scale: Vertical scaling (adding power to Scale: Horizontal scaling (adding more
a single server). servers to a distributed system).
Query Language: SQL (Structured Query Query Language: Varies; can be SQL-
Language). like or specialized query languages.
Mongo DB 2
Flexibility: SQL is rigid; NoSQL is flexible, suitable for evolving data models.
MongoDB terminologies
graph TD
id1[(Database)] --collections-->id3(students) & id4(Teache
id3 --> id31[document]
id4 --> id41[document]
id5 --> id51[document]
JSON vs BSON
In mongo dB, we write JSON format only but behind the scene data is stored in
BSON (binary json) format, Using BSON mongo dB can achieve higher read and
write speeds, reduce stroage requirements, improved data manipulation
capabilities
INSTALLATION
1. Download MongoDB:
Visit the MongoDB download page and select the appropriate version
for Windows.
2. Install MongoDB:
3. Start MongoDB:
Mongo DB 3
MongoDB should start automatically after installation. If not, you can
start it manually by running the mongod command in the Command
Prompt.
4. Connect to MongoDB:
CRUD OPERATIONS
To see all databases
To create database
To delete database
test> db.dropDatabase();
test> db.createCollection('<collection-name>');
Mongo DB 4
To delete a collection
test> db.<collection-name>.drop();
Insert Operation
student> db.collectionName.insertOne({
key1: value1,
key2: value2,
// Additional fields as needed
});
student> db.collectionName.insertMany([
{
key1: value1,
key2: value2,
// Additional fields as needed
},
{
key1: value1,
key2: value2,
// Additional fields as needed
},
// Additional documents
]);
Search Operations
Mongo DB 5
student> db.<collectionName>.find();
student> db.<collectionName>.findOne({"name":"vinod"});
Update Operations
db.<collectionName>.updateOne(
{ key: value },
{ $set: { updatedKey: updatedValue } }
);
db.<collectionName>.updateMany(
{ key: value },
{ $set: { updatedKey: updatedValue } }
);
Mongo DB 6
Removing Fields
db.mycollection.updateMany(
{filter}, // Empty filter matches all documents
{ $unset: { fieldName: 1 } }
);
Rename Fields
db.mycollection.updateMany(
{filter}, // Empty filter matches all documents
{ $rename: { "oldFieldName": "newFieldName" } }
);
db.collectionName.updateOne(
{ filter },
{ $push: { arrayfield: "Newelement" } }
);
db.collectionName.updateOne(
{ filter },
{ $pull: { arrayfield: "value" } }
);
Mongo DB 7
db.books.update(
{ _id: 1, "authors": "Author2" },
{ $set: { "authors.$": "UpdatedAuthor2" } }
);
Deletion Operations
OR
The --jsonArray option simplifies the mongoimport process by indicating that the
input JSON file is a single array, where each element becomes a separate
document in the MongoDB collection. Use it for datasets structured as arrays of
objects.
Mongo export
To export data from MongoDB, you can use the mongoexport tool. This tool allows
you to export data from a collection into a JSON, CSV, or TSV file.
Mongo DB 8
mongoexport --db <databaseName> --collection <collectionName>
Comparison Operators
Equality
Inequality
Greater Than
$gte : Matches values that are greater than or equal to a specified value.
Less than
Mongo DB 9
$lt : Matches values that are less than a specified value.
$lte : Matches values that are less than or equal to a specified value.
IN
Not IN
Modulus
$mod : Performs a modulus operation on the field value and selects documents
with a specified remainder.
Regualr Expression
Mongo DB 10
Cursors
In MongoDB, a cursor is a pointer to the result set of a query. When you query a
MongoDB collection, the result set can be quite large, and it might not fit
entirely in memory. To efficiently handle large result sets, MongoDB uses
cursors to retrieve a small batch of documents at a time.
Cursor methods
next() Method:
The next() method retrieves the next document from the result set.
forEach() Method:
hasNext() Method:
The hasNext() method checks if there are more documents in the result
set.
Mongo DB 11
// Do something with the document
}
toArray() Method:
limit() Method:
skip() Method:
sort() Method:
The sort() method sorts the result set based on one or more fields.
count() Method:
The count() method returns the number of documents in the result set
without retrieving them.
distinct() Method:
Mongo DB 12
The distinct() method returns an array of distinct values for a specified
field.
Logical Operators
AND $and
db.collection.find({
$and: [
{ field1: value1 },
{ field2: value2 }
]
});
OR $or
db.collection.find({
$or: [
{ field1: value1 },
{ field2: value2 }
]
});
NOT $not
db.collection.find({
field: { $not: { $eq: value } }
});
Complex Expressions
Mongo DB 13
The $expr operator in MongoDB is used to evaluate expressions within the
query language. It allows you to use aggregation expressions to compare
values in the same document during the query stage. This operator is
particularly useful when you need to compare fields within the same document
or perform more complex evaluations that go beyond the capabilities of regular
query operators.
The $expr operator in MongoDB is used to evaluate expressions within the
query language. It allows you to use aggregation expressions to compare
values in the same document during the query stage. This operator is
particularly useful when you need to compare fields within the same document
or perform more complex evaluations that go beyond the capabilities of regular
query operators.
Here's a basic example to illustrate the use of $expr :
db.sales.find({
$expr: {
$gt: ["$salesAmount", "$targetAmount"]
}
});
In this example, the query retrieves documents from the "sales" collection
where the value of the "salesAmount" field is greater than the value of the
"targetAmount" field within the same document.
Elements Operators
Equality ( $eq ) Operator:
Mongo DB 14
// Documents where the "field" exists
db.collection.find({ field: { $exists: true } });
Mongo DB 15
// Documents where the "field" array has at least one el
ement greater than 10
db.collection.find({ field: { $elemMatch: { $gt: 10 } }
});
Projections
projections refer to the mechanism of specifying which fields of a document
should be included or excluded in the result set of a query. Projections allow
you to shape the output of your queries by determining which fields are
returned and which are omitted.
To include specific fields in the result set, you specify the field names with a
value of 1 :
Embedded Documents
Query by Embedded Field:
Mongo DB 16
Query by Multiple Embedded Fields:
Indexes
indexes are data structures that improve the speed of data retrieval operations
on a MongoDB database. Indexes are similar to the indexes found in books:
Mongo DB 17
they provide a quick way to look up information based on the values of specific
fields. Without indexes, MongoDB would have to perform a collection scan,
which can be slow and resource-intensive, especially as the size of the
collection grows.
db.products.createIndex({field:1})
//1 for ascending order and -1 for descending order
db.collection.getIndexes()
db.collection.dropIndex({field:1})
db.collection.dropIndex("index_name")
db.collection.createIndex({field:1}, {Unique:true})
db.collection.createIndex({field:"text"})
db.products.find({field{$regex:"air"}}) //slower
db.collection.find( $text: {$search:"keyboard"}})
Mongo DB 18
Aggregation
Aggregation in MongoDB refers to the process of transforming and
manipulating documents in a collection to produce computed results. The
aggregation framework is a powerful and flexible tool that enables you to
perform data transformations, group data, filter data, and compute
aggregations on documents. It is a pipeline-based framework that processes
documents through a sequence of stages, allowing you to perform complex
transformations on your data.
db.collection.aggregate([
{ $match: { field: value } }
]);
db.collection.aggregate([
{ $group: { _id: "$field", count: { $sum: 1 } } }
]);
db.collection.aggregate([
{ $project: { newField: "$oldField", _id: 0 } }
]);
db.collection.aggregate([
{ $sort: { field: 1 } }
Mongo DB 19
]);
db.collection.aggregate([
{ $limit: 10 },
{ $skip: 5 }
]);
db.collection.aggregate([
{ $unwind: "$arrayField" }
]);
db.orders.aggregate([
{
$lookup:
{
from: "products",
localField: "productId",
foreignField: "_id",
as: "product"
}
}
]);
Example of aggregation
Mongo DB 20
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "product"
}
},
{
$unwind: "$product"
},
{
$group: {
_id: "$product.category",
totalRevenue: { $sum: { $multiply: ["$quantity", "$prod
}
},
{
$sort: { totalRevenue: -1 }
}
]);
MongoDB atlas
MongoDB Atlas is a fully-managed, cloud-based database service by
MongoDB, Inc., offering a hassle-free way to deploy and scale MongoDB
databases on popular cloud platforms. It handles routine operational tasks,
such as backups, security, and scaling, allowing developers to focus on
building applications. With support for major cloud providers, robust security
features, automated backups, and real-time monitoring, MongoDB Atlas
provides an efficient and scalable solution for deploying MongoDB databases in
the cloud, suitable for a wide range of applications.
MongoDB Compass
Mongo DB 21
MongoDB Compass is the official graphical user interface for MongoDB,
offering an intuitive visual environment to explore and interact with MongoDB
databases. With features like schema analysis, query building, index
management, and real-time performance monitoring, Compass simplifies
database tasks for both developers and non-developers. It provides a user-
friendly interface to visualize and edit data, build aggregation pipelines, and
connect seamlessly to MongoDB Atlas. Whether examining data structures,
executing queries, or managing security settings, MongoDB Compass
enhances the MongoDB experience through a graphical and accessible
interface.
MongoDB Drivers
MongoDB drivers are language-specific tools that facilitate communication
between applications and MongoDB databases. They offer a simplified
interface for developers to perform common database operations (e.g., CRUD
tasks), manage connections, handle data serialization, and ensure secure
interactions. These drivers, available for various programming languages,
abstract the complexities of interacting with MongoDB, allowing developers to
work with the database using familiar language-specific syntax and
conventions.
Python
PyMongo
Mongo DB 22