Menu

Understanding CRUD Operations

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:

db.student.insert({
    regNo: "3014",
    name: "Test Student",
    course: {
        courseName: "MCA",
        duration: "3 Years"
    },
    address: {
        city: "Bangalore",
        state: "KA",
        country: "India"
    }
})

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.

db.collection_name.find()

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.

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

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:

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

MongoDB: Updating a document in a collection(Update)

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

db.collection_name.update()

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.

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

You will see the following in the Command Prompt:

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:

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

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

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