CRUD Operation in MongoDB
As we know that we can use MongoDB for various things like building an application (including web and mobile), or analysis of data, or administrator of a MongoDB database, in all these cases we need to interact with the MongoDB server to perform certain operations like entering new data into the application, updating data into the application, deleting data from the application, and reading the data of the application.
MongoDB provides a set of some basic but essential operations that will help you to easily interact with the MongoDB server and these operations are known as CRUD operations.
C - Create
R - Read
U - Update
D - Delete
Create Operations
The create or insert operations are used to insert or add new documents in the collection. If a collection does not exist, then it will create a new collection in the database. You can perform, and create operations using the following methods provided by MongoDB:
Method | Description |
db.collection.insertOne() | It is used to insert a single document in the collection. |
db.collection.insertMany() | It is used to insert multiple documents in the collection. |
db.createCollection() | It is used to create an empty collection. |
mongosh> use class
switched to db class
Example 1: In this example, we are inserting details of a single student in the form of a document in the student collection using db.collection.insertOne() method.
class> db.students.insertOne({name:"Sumit",age:20,branch:"CSE",course:"C++",mode:"online",paid:true,amount:1499})
{
acknowledged: true,
insertedId: ObjectId("64be4d56d60305991bf7eeff")
}
Example 2: In this example, we are inserting details of multiple students in the form of documents in the student collection using db.collection.insertMany().
class> db.students.insertMany([{ name: "Rohit", age: 20, branch: "IT", course: "Python", mode: "online", paid: false, amount: 1999 }, { name: "Mohit", age: 20, branch: "EXTC", course: "Java", mode: "online", paid: true, amount: 1499 }, { name: "Amit", age: 20, branch: "IT", course: "Data Structure", mode: "online", paid: false, amount: 2499 }])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64be4f7fd60305991bf7ef06"),
'1': ObjectId("64be4f7fd60305991bf7ef07"),
'2': ObjectId("64be4f7fd60305991bf7ef08")
}
}
Example 3: Empty collection created using db.createCollection() method.
class> db.createCollection("CollectionName")
{ ok: 1 }
class> show collections
CollectionName
students
Read Operations
The Read operations are used to retrieve documents from the collection, or in other words, read operations are used to query a collection for a document. You can perform read operations using the following method provided by MongoDB:
Method | Description |
db.collection.find() | It is used to retrieve documents from the collection. |
Example: In this example, we are retrieving the details of students from the student collection using db.collection.find() method.
class> db.students.find()
[
{
_id: ObjectId("64be4d56d60305991bf7eeff"),
name: 'Sumit',
age: 20,
branch: 'CSE',
course: 'C++',
mode: 'online',
paid: true,
amount: 1499
},
{
_id: ObjectId("64be4e4fd60305991bf7ef00"),
name: 'Rohit',
age: 20,
branch: 'IT',
course: 'Python',
mode: 'online',
paid: false,
amount: 1999
},
{
_id: ObjectId("64be4e4fd60305991bf7ef01"),
name: 'Mohit',
age: 20,
branch: 'EXTC',
course: 'Java',
mode: 'online',
paid: true,
amount: 1499
},
{
_id: ObjectId("64be4e4fd60305991bf7ef02"),
name: 'Amit',
age: 20,
branch: 'IT',
course: 'Data Structure',
mode: 'online',
paid: false,
amount: 2499
}
]
Update Operations
The update operations are used to update or modify the existing document in the collection. You can perform update operations using the following methods provided by MongoDB:
Method | Description |
db.collection.updateOne() | It is used to update a single document in the collection that satisfies the given criteria. |
db.collection.updateMany() | It is used to update multiple documents in the collection that satisfy the given criteria. |
db.collection.replaceOne() | It is used to replace a single document in the collection that satisfy the given criteria. |
Example 1: In this example, we are updating the age of Sumit in the student collection using db.collection.updateOne().
class> db.students.updateOne({name:"Sumit"},{$set:{age:24}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
class> db.students.find({name:"Sumit"}).pretty()
[
{
_id: ObjectId("64be4d56d60305991bf7eeff"),
name: 'Sumit',
age: 24,
branch: 'CSE',
course: 'C++',
mode: 'online',
paid: true,
amount: 1499
}
]
Example 2: In this example, we are updating the year of the course in all the documents in the student collection using db.collection.updateMany() method.
class> db.students.updateMany({},{$set:{year:2023}})
{
acknowledged: true,
insertedId: null,
matchedCount: 10,
modifiedCount: 10,
upsertedCount: 0
}
class> db.students.find().pretty()
[
{
_id: ObjectId("64be4d56d60305991bf7eeff"),
name: 'Sumit',
age: 24,
branch: 'CSE',
course: 'C++',
mode: 'online',
paid: true,
amount: 1499,
year: 2023
},
{
_id: ObjectId("64be4e4fd60305991bf7ef00"),
name: 'Rohit',
age: 20,
branch: 'IT',
course: 'Python',
mode: 'online',
paid: false,
amount: 1999,
year: 2023
},
{
_id: ObjectId("64be4e4fd60305991bf7ef01"),
name: 'Mohit',
age: 20,
branch: 'EXTC',
course: 'Java',
mode: 'online',
paid: true,
amount: 1499,
year: 2023
},
{
_id: ObjectId("64be4e4fd60305991bf7ef02"),
name: 'Amit',
age: 20,
branch: 'IT',
course: 'Data Structure',
mode: 'online',
paid: false,
amount: 2499,
year: 2023
}
]
Example 3:
class> db.students.replaceOne({name:"Sumit"},{name:"Sonu",age:22,branch:"MECH",course:"Data Science",mode:"Online",paid:false,amount:3000})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
class> db.students.find({name:"Sonu"}).pretty()
[
{
_id: ObjectId("64be4d56d60305991bf7eeff"),
name: 'Sonu',
age: 22,
branch: 'MECH',
course: 'Data Science',
mode: 'Online',
paid: false,
amount: 3000
}
]
Embedded Documents
MongoDB provides you with a cool feature which is known as Embedded or Nested Document. Embedded documents or nested documents are those types of documents that contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents.
Syntax:
{
....
field: {field1: value1, field2: value2}
....
}
Example 1:
class> db.students.insertOne({name:{first:"Anil",middle:"Kumar",last:"Singh"},branch:"IT",courseName:"C",courseType:"Free"})
{
acknowledged: true,
insertedId: ObjectId("64be571cd60305991bf7ef09")
}
class> db.students.find({courseType:"Free"}).pretty()
[
{
_id: ObjectId("64be571cd60305991bf7ef09"),
name: { first: 'Anil', middle: 'Kumar', last: 'Singh' },
branch: 'IT',
courseName: 'C',
courseType: 'Free'
}
]
Example 2:
class> db.students.insertOne({name:{first:"Pawan",middle:"Kumar",last:"Singh"},branch:"CSE",courseDetails:{name:"Python Backend Development",startingDate:"March 28,2023"},state:"MH"})
{
acknowledged: true,
insertedId: ObjectId("64be5cbed60305991bf7ef0a")
}
class> db.students.find({state:"MH"}).pretty()
[
{
_id: ObjectId("64be5cbed60305991bf7ef0a"),
name: { first: 'Pawan', middle: 'Kumar', last: 'Singh' },
branch: 'CSE',
courseDetails: {
name: 'Python Backend Development',
startingDate: 'March 28,2023'
},
state: 'MH'
}
]
Delete Operations
The delete operation is used to delete or remove the documents from a collection. You can perform delete operations using the following methods provided by MongoDB:
Method | Description |
db.collection.deleteOne() | It is used to delete a single document from the collection that satisfies the given criteria. |
db.collection.deleteMany() | It is used to delete multiple documents from the collection that satisfy the given criteria. |
Example 1: In this example, we are deleting a document from the student collection using db.collection.deleteOne().
db.students.deleteOne({name:"Sumit"})
{ acknowledged: true, deletedCount: 0 }
class> db.students.find().pretty()
[
{
_id: ObjectId("64be4d56d60305991bf7eeff"),
name: 'Sonu',
age: 22,
branch: 'MECH',
course: 'Data Science',
mode: 'Online',
paid: false,
amount: 3000
},
{
_id: ObjectId("64be4f7fd60305991bf7ef06"),
name: 'Rohit',
age: 20,
branch: 'IT',
course: 'Python',
mode: 'online',
paid: false,
amount: 1999,
year: 2023
},
{
_id: ObjectId("64be4f7fd60305991bf7ef07"),
name: 'Mohit',
age: 20,
branch: 'EXTC',
course: 'Java',
mode: 'online',
paid: true,
amount: 1499,
year: 2023
},
{
_id: ObjectId("64be571cd60305991bf7ef09"),
name: { first: 'Anil', middle: 'Kumar', last: 'Singh' },
branch: 'IT',
courseName: 'C',
courseType: 'Free'
},
{
_id: ObjectId("64be5cbed60305991bf7ef0a"),
name: { first: 'Pawan', middle: 'Kumar', last: 'Singh' },
branch: 'CSE',
courseDetails: {
name: 'Python Backend Development',
startingDate: 'March 28,2023'
},
state: 'MH'
}
]
Example 2: In this example, we are deleting all the documents from the student collection using db.collection.deleteMany() method.
db.students.deleteMany({})
{ acknowledged: true, deletedCount: 5 }
class> db.students.find().pretty()