Creating a Database in MongoDB
MongoDB is a NoSQL document-based database that stores data in a flexible, JSON-like
format called BSON (Binary JSON). Unlike traditional relational databases, MongoDB
doesn’t require a predefined schema, which allows you to quickly change your database
structure as your application evolves. Here's a step-by-step description of how to create a
database and perform some basic operations in MongoDB.
1. Setting Up MongoDB
Before you can create a database, ensure you have MongoDB installed on your system. You
can install MongoDB from the official website or use services like MongoDB Atlas for
cloud-based database hosting.
Once MongoDB is installed and running, you can interact with it through the Mongo Shell or
through programming languages (like Node.js, Python, etc.).
To start MongoDB (assuming it's installed on your local machine), you can use the following
commands:
# Start MongoDB service
mongod
To interact with MongoDB:
# Open MongoDB shell
Mongo
2. Creating a Database
In MongoDB, creating a database is simple. Unlike relational databases, you don’t explicitly
create a database using a CREATE DATABASE statement. Instead, MongoDB automatically
creates the database when you first insert data into it.
To create a database, use the following command in the Mongo Shell:
use myDatabase
3. Creating Collections
A collection in MongoDB is analogous to a table in a relational database. You can create
collections within a database to store documents (records).Once you're inside a database (like
myDatabase), you can create a collection by simply inserting data into it. Here’s how you can
do that:
db.createCollection("students")
MONGODB COMMANDS TO PERFORM UPDATE AND DELETE DOCUMENT
Update and Delete Commands in MongoDB
DESCRIPTION :
In MongoDB, update and delete operations are used to modify and remove documents from
collections. Here’s a clear explanation of both:
UPDATE Command
Purpose:
To modify existing documents in a collection.
Syntax:
db.collection.updateOne(filter, update, options)
db.collection.updateMany(filter, update, options)
Examples:
1. Update one document:
db.students.updateOne(
{ name: "John" },
{ $set: { grade: "A" } }
)
This sets grade = "A" for the first document with name = "John".
2. Update multiple documents
db.students.updateMany(
{ class: "10th" },
{ $inc: { marks: 5 } }
)
DELETE Command
Purpose:
To remove documents from a collection.
Syntax:
db.collection.deleteOne(filter)
db.collection.deleteMany(filter)
Examples:
1. Delete one document:
db.students.deleteOne({ name: "Alice" })
Deletes the first document where name = "Alice".
2. Delete multiple documents:
db.students.deleteMany({ grade: "F" })
Deletes all documents where grade = "F".