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)
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:
name: "Test Student",
duration: "3 Years"
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.
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.
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:
Note that after running the
remove() method, the entry has been deleted from the student collection.