In previous articles, we have
talked about installation, database, collection, and document, now we will learn
to perform basic CRUD operations on Documents in MongoDB
Create Document
Creating a document refers to inserting a document in the collection, let’s see how it happens
Considering we are creating records for employees, we are going to insert below two
documents in the employee collection
({"empid" :
"1234","empname" : "Rajesh", "empunit":
"Finance"})
({"empid"
: "1235","empname" : "Mani", "empunit"
: "HR"})
Read Document
Now
we will see how to pull this data from collection, we have a function
db.<collection>.find()
We can
use different versions of find function
i.e.
db.<collection>.find() : finds
all documents in collection
db.<collection>.findOne() : find
single document
db.<collection>.find(<condition>) : find
particular document/s which satisfies condition
Updating Document
Definition
of the update remains same as oracle update definition, i.e. setting up new value to attribute
or parameter
let’s
update the empname of an employee having id 1234 to Ramesh, so the query will be
db.employee.update ({"empid" :
"1234"}, {$set: {"empname" : "Ramesh"}});
Delete Document
Syntax
for deleting of document from collection is db.<collection>.remove()
let’s
try deleting employee with empid 1235
We can
see the entry is deleted. Similar way we can execute db.<collection>.remove() without any condition in a bracket to
remove all the documents in the collection.
[Aslo read- Introduction to Mongodb]