What is MongoDB?
The name MongoDB is derived from the word humongous, indicating its ability to store large amounts of data.
How It Works
MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON).
Data Structure Overview
-------------------
| Database | Shop |
-------------------
| Collections | Users, Orders |
-------------------
| Document | { name: "Kasun" } |
--------------------------------------
Each document is a record stored in BSON format. Documents can also be nested or embedded:
{
"name": "Kasun",
"address": {
"city": "Colombo"
}
}
Relations
MongoDB has no or few relations. Relational data must be handled manually.
If you use Mongoose (a popular ODM for Node.js), you can reference documents using the .populate()
method:
this.UserDocument.find().populate("AddressId").exec();
How to Set Up MongoDB Locally
Follow the official documentation to install MongoDB on your platform:
π https://www.mongodb.com/docs/manual/installation/
Alternatively, use MongoDB Atlas, a free cloud-based database that does not require local setup or server deployment.
Setting Up a Client
You can use MongoDB Compass (GUI client) or any other GUI tool to connect and manage your database.
π Recommended: MongoDB Compass
These tools help visualize how data is stored in BSON format.
Connecting MongoDB to Your Application
MongoDB supports drivers and SDKs for all major programming languages.
π Driver documentation: https://www.mongodb.com/docs/drivers/
Accessing MongoDB via CLI
You can use the Mongo Shell to interact with your database via the command line. This is useful for simple operations or writing scripts.
Common MongoDB CLI Commands
- List all databases:
show dbs
- Switch to a database (creates it if it doesn’t exist):
use first-test
- Insert a document into a collection (creates the collection if it doesnβt exist):
db.users.insertOne({ name: "Kasun", age: 28 })
- Show all collections:
show collections
- Find all documents in a collection:
db.users.find()
- Query by specific attribute (e.g., age > 25):
db.users.find({ age: { $gt: 25 } })
- Query nested fields:
db.users.find({ "address.city": "Colombo" })