Signup/Sign In

CRUD Operations in MongoDB

CRUD operations refer to the basic Insert, Read, Update and Delete operations. In the previous chapter, we learnt about how to create a database and drop the database in MongoDB. Now, let us learn how to perform CRUD (Create/Read/Update/Delete) operations in MongoDB.

MongoDB: Inserting a document into a collection(Create)

The command db.collection.insert() will perform an insert operation into a collection of a document.

Let us insert a document to a student collection. You must be connected to a database for doing any insert. It is done as follows:

	regNo: "3014",
	name: "Test Student",
	course: {
		courseName: "MCA",
		duration: "3 Years"
	address: {
		city: "Bangalore",
		state: "KA",
		country: "India"

Inserting data into MongoDB Collection

Note that an entry has been made into the collection called student.

MongoDB: Querying a document from a collection(Read)

To retrieve (Select) the inserted document, run the below command. The find() command will retrieve all the documents of the given collection.


Selecting document from MongoDB Collection

NOTE: Please observe that the record retrieved contains an attribute called _id with some unique identifier value called ObjectId which acts as a document identifier.

If a record is to be retrieved based on some criteria, the find() method should be called passing parameters, then the record will be retrieved based on the attributes specified.


For Example: Let us retrieve the record from the student collection where the attribute regNo is 3014 and the query for the same is as shown below:


MongoDB: Updating a document in a collection(Update)

In order to update specific field values of a collection in MongoDB, run the below query.


update() method specified above will take the fieldname and the new value as argument to update a document.

Let us update the attribute name of the collection student for the document with regNo 3014.

	"regNo": "3014"	

Updating document from MongoDB Collection

You will see the following in the Command Prompt:

Updating document from MongoDB Collection

MongoDB: Removing an entry from the collection(Delete)

Let us now look into the deleting an entry from a collection. In order to delete an entry from a collection, run the command as shown below:


For Example: db.student.remove({"regNo":"3014"})

Removing document from MongoDB Collection

Note that after running the remove() method, the entry has been deleted from the student collection.