CRUD Operations in MongoDB

Welcome to a tutorial on CRUD Operations in MongoDB. Here you will learn how to perform CRUD (Create/Read/Update/Delete) operations in MongoDB.

 

Inserting a document into a collection(Create)

The command db.collection.insert() when used performs an insert operation into a collection of a document.

Now, let's insert a document into a student collection. But, first, you must be connected to a database. This is shown below.

db.student.insert({
	regNo: "3014",
	name: "Test Student",
	course: {
		courseName: "MCA",
		duration: "2 Years"
	},
	address: {
		city: "Sydney",
		state: "SY",
		country: "Australia"
	}
})

You can observe that an entry has been made into the collection called student.

 

Querying a document from a collection(Read)

In MongoDB, to retrieve (or Select) the inserted document, you can run the command below. 

db.collection_name.find()

 

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

But, if a record is to be retrieved based on certain criteria, the find() method should be called passing parameters, after which the record will be retrieved based on the attributes specified.

db.collection_name.find({"fieldname":"value"})

 

Take this example: If we retrieve the record from the student collection where the attribute regNo is 3014 and the query for the same is as shown below:

 db.students.find({"regNo":"3014"})

 

Updating a document in a collection(Update)

For us to update specific field values of a collection in MongoDB, we can run the query below.

 db.collection_name.update()

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

Now, let’s update the attribute name of the collection student for the document with regNo 3014.

 db.student.update({
	"regNo": "3014" 
},
$set:
{
	"name":"Justin"
})

 

Removing an entry from the collection(Delete)

For you to delete an entry from a collection, you should run the command as shown below:

 db.collection_name.remove({"fieldname":"value"})

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