1/1/1970
Manual 👉 MongoDB Manual
to MongoDB comparison:
| Relational DB | MongoDB | Description |
|---|---|---|
| Database | Database | A collection of related data stored in one place. |
| Table | Collection | A grouping of related data (like a table in SQL). |
| Row | Document | An individual record in the collection. |
| Column | Field | A key-value pair within a document. |
Mac
Official website > Products > Community Server : Download
extract downloaded file mongodb-macos--xxx
in mongodb-macos-xxx/bin there are three executive file.
install_compassmongod : mongo demon (Main file that is useful to process mongodb in pc)mongosCreate Directory where you want to store database let Users/Harry/db
Open Terminal in mongod-macos-xxx/bin folder
type mongod --dbpath /Users/Harry/db
for more help ./mongod --help
Window
MongDBxxx.msi setupNote: In Window's mongodb Community Server , compass is automatically installed ( but if not, then install it manually )
Mac/Window
| Aspect | JSON | MongoDB (BSON) |
|---|---|---|
| Format Type | Text-based, human-readable. | Binary, designed for efficient storage and traversal. |
| Data Representation | Pure JSON (e.g., {"key": "value"}). |
BSON (Binary JSON) with extended support for types. |
| Supported Data Types | Limited to basic types (string, number, array, object). | Includes additional types like Date, ObjectId, binary data, etc. |
| Size Efficiency | Larger in size due to text representation. | Smaller due to binary encoding and optimized storage. |
| Usage | Data exchange (e.g., APIs, config files). | Data storage and manipulation in MongoDB collections. |
| Example | {"name": "John", "age": 30, "active": true} |
{"_id": ObjectId("507f1f77bcf86cd799439011"), "name": "John", "age": 30} |
JSON strictly adheres to its specification, which mandates that field names (keys) must be strings enclosed in double quotes.
Example:
{
"name": "John",
"age": 30,
"active": true
}In MongoDB's shell, objects are represented using JavaScript object notation, which follows JavaScript syntax rules.
JavaScript does not require quotes around field names unless the name contains special characters (e.g., spaces, hyphens).
Example:
{
name: "John",
age: 30,
active: true
}JSON field names must have quotes (for strict adherence to the JSON standard).
MongoDB shell allows omitting quotes for simplicity unless the field name has special characters or conflicts with JavaScript reserved words. For example:
{ "first-name": "John", "age": 30 } // Quotes required for "first-name".Launch Compass Application
mongodb://localhost:27016 (Default).xxx27016Note: Compass will only work, if Mongodb server is running in background other wise Error connect ECONNREFUSED 127.0.0.1:27017, that means no instance 127.xxx server is running.
Create Databases
employee & Collection Name let managersAdd Data
employees.managersobjects/documents DynamicallyAdd Data > Insert Document{
"_id":{
"$oid": "644319dc47........"
},
"name": "Rohan",
"role": "Programmer"
}Note: Like Relational Database, we do not require Schema in collections. This is The beauty of MongoDB or NoSQL
So next time you need not to follow the structure
Add Data > Insert Document{
"_id":{
"$oid": "644319dc47........"
},
"name": "Harry",
"location": "San Francisco"
}Standard connection String Format
mongodb://[username:password@]host1[:port1[,...hostN[:portN]][/[defaultauthdb][?options]]
Note: Local Host URI is not secured with username and Password
In Compass a Document Look like
_id: objectId('644xxxxxxxxx)
item : "canvas"
qty: 100
tags:Array
0: "cotton"
size: object
h:28
w:35.5
uom: "ch"where
_id -> Document/Object unique Id
{} -> object
[] -> Array
"" -> String value
To run MongoDB (in Terminal/Shell)
mongo sh
show dbs # show all the databases
use employee # use database named 'employee'Note:
use <database> Create a new database if it is not presentdatabaseName.collectionName.func({}). However, using use <database> sets the context to that database, allowing us to use the shorthand db.collectionName.func({}) without explicitly mentioning the database name each time.(Run these commands in MongoDB Shell or Terminal )
Summary
db.collection.insertOne()
db.collection.insertMany()
db.collection.find({..}) db.collection.findOne() db.collection.updateOne() db.collection.updateMany() db.collection.ReplaceOne()*db.collection.deleteOne() db.collection.deleteMany() db.collection.remove()` *
Insert One db.collection.insertOne()
// inserts a single document into `inventory` collection
db.inventory.insertOne(
{item: "canvas", qty:100, tags:["cotton"], size:{h :28, w:35.5, uom:"cm:"}}
)Insert Many db.collection.insertMany()
// inserts multiple document into `inventory` collection on , Pass an array of documents to the method.
db.inventory.insertMany(
[{item: "canvas1", qty:100, tags:["Zinc"]},
{item: "canvas2", qty:100, tags:["copper"]},
{item: "canvas3", qty:100, tags:["Aluminium"]}]
)Note:
db.collection.insertOne() in MongoDB shell where db refers to the current active database.databaseName.collection.insertOne() in programming contexts to explicitly reference a specific database object.Find `db.collection.find({..})
// Fetch all documents from `inventory` collection
db.inventory.find() // All documents
// or db.inventory.find({})
// WHERE
db.inventory.find({qty:30}) // Where qty=30
// AND
db.inventory.find({status:"A", qty:30}) // Where qty=30 and status = "A"
// OR
db.inventory.find({tags: {$or: ["zinc", "copper"]}}) // Where tags="zinc" or tags="copper
// IN
db.inventory.find({tags: {$in: ["zinc", "copper"]}}) // Where value of a 'tags' field matches element any element from the array. Same as tags="zinc" or tags="copper
// Less Then
db.inventory.find({status:"A", qty:{$lt:30}}) // where status="A" and qty<`30`// AND
db.inventory.find({$and:[{tags:"copper"}, {tags: "zinc"}]}) // where `tags` is array and contain both `"copper"` and `"zinc"
// ALL (Same as above)
db.inventory.find({tags:{$all:["copper", "zinc"]}}) // where `tags` is array and contain both `"copper"` and `"zinc"Find One db.collection.findOne()
// retrieves only the first document
db.inventory.findOne({status:{$in:["A", "D"]}}) // where status= "A" or "D"Note: find() In terminal give output as java script array. while findOne() pull directly a document.
Query Selectors: used to filter MongoDB documents effectively
{ field: value } (Exact match)$eq, $ne (Equal, Not equal)$gt, $gte, $lt, $lte$in, $nin (In/Not in array)$and, $or, $not, $nor$exists (Field exists or not)$type (Field type)$regex (Pattern match)$elemMatch, $size (Match array elements, Array length)Update One db.collection.updateOne()
// Update the First documennt.
db.inventory.updateOne(
{ item: "paper" }, // Where item = "paper"
$set: { "size.uom": "cm", status:"P"}, // <- Set to
$currentDate: {lastModified: true } // $currDate set the lastModified field to Current Date.Note: During updated, if field is not exist, it will create the field and add the entry.
Update Many db.collection.updateMany()
// Update the First documennt, based on specified condition
db.inventory.updateMany{
{"qty":{$lt: 50}}, // Where qty < 50
{
$set: {"size.uom" : "in", status: "P"}, // <- Set to
$currentDate: { lastModified: true}
}
}Replace One db.collection.ReplaceOne()
// Replaces a single document withing the collection base on the filter
db.collection.replaceOne{
<filter> // document
<replacement>, // document
{
upsert: <boolean>, // boolean
writenConcern: <document>,
collation: <document>,
hint: <document | string>
}
}**Delete Many db.collection.deleteMany()
// Delete all documents that match a specified filter.
db.inventory.deleteMany({})
db.inventory.deleteMany({status : "A"}) // where status="A"
Delete One db.collection.deleteOne()
// Delete at single first document that match a specified filter.
db.inventory.deleteOne()
db.inventory.deleteOne({status : "A"}) // where status="A"Note:
Remove db.collection.remove()
// Delete a single document or all documents that match a specified filter.Note: remove return the document, while delete return boolean 1, if founds and delete the document.
Differ
Sort db.collection.find().sort()
// Sort the output
db.inventory.find().sort({qty:1}) // Ascending of 'qty'
db.inventory.find().sort({qty:-1}) // Descending of 'qty'Skip db.collection.find().skip()
db.inventory.find().skip(2) // skip first 2 documentLimit db.collection.find().limit()
db.inventory.find().limit(3) // Limits the no. of document's output to 2// Show 8 blogs per page
db.blogs.find().skip((PageNo-1)*8).limit(8)
// Page 1 : skip (1-1)*8=0, limit 8 : blog no. 1-8
// Page 2 : skip (2-1)*8=8, limit 8 : blog no. 9-16
// Page 2 : skip (3-1)*8=16, limit 8 : blog no. 17-24Database Page, through Left side Panel Option+CREATE , to Create a new ClusterShared Cluster (out of three Serverless, Dedicated, Shared) to use a Free ClusterServer Location (Nearest location to user is preferred)Cluster NameCreate ClusterDatabase Access Page, through Left side Panel OptionsPassword AuthenticatonUser Name and PasswordAdd UserDatabase Page, Click on Connect button corresponding to the cluster you want to connectDriver OptionCompass, choose the version of your local Compassconnection stringmongodb+srv://<username>:<password>@<cluster-url>/<database><username>: Your MongoDB Atlas username.<password>: Your MongoDB Atlas password.<cluster-url>: The cluster URL provided by Atlas (e.g., cluster0.mongodb.net).<database>: The specific database you want to connect to (optional; you can also leave it empty to connect to the default).user from Database Access Pagemongodb+srv://gaurav28official:gk123@MyNotes.d8ustvt.mongodb.net/mernNotesURI in your Local Compass app to ConnectHurray, You Can access your cloud database through Compass : )
Note: in free Plan you can Create one cluster at a time, to make a new one, you need to terminate the existing cluster
The aggregation pipeline in MongoDB is a powerful framework for data aggregation operations, similar to SQL's GROUP BY and aggregate functions. It allows you to process and transform documents in a collection through a series of stages. Each stage performs an operation on the data, such as filtering, grouping, or transforming, and passes the result to the next stage in the pipeline.
Common Aggregation Stages:
$match - Filters documents by specified criteria (like WHERE in SQL).$group - Groups documents by a specified field and performs calculations, like SUM, AVG, COUNT, etc.$sort - Sorts documents by specified fields.$project - Reshapes documents, including or excluding fields.$limit and $skip - Limits or skips a certain number of documents.Example: To find the total sales amount grouped by each product category, the pipeline might look like this:
db.sales.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$category", totalSales: { $sum: "$amount" } } },
{ $sort: { totalSales: -1 } }
])This example:
category and sums the amount for each.totalSales in descending order.More