MongoDB CRUD Operations
MongoDB stores data in the form of documents. All the documents are JSON, like key and value pairs. MongoDB documents are BSON document (BSON is a binary representation of JSON document.). The value of the field can be any of the BSON data types. A field can be anything, it can be a singular value (like integer or double, string) or can be a document itself or can be an array of documents. CRUD operations refer to the basic Insert, Read, Update and Delete operations. In the previous chapter, let us learn how to perform CRUD (Create/Read/Update/Delete) operations in MongoDB.
Inserting a document into a collection (Create):
The command db.collection.insert() will perform an insert operation into a collection of a document.
In below command:
db: stands for the database (database currently being used)
collection name: the prefered collection (on relational database it is a table) you want to insert.
insert: It is the method to create new record. It accepts a BSON document.
If you have a situation where you are inserting multiple documents into a collection, you can make the insert faster by using batch inserts. Batch inserts
allow you to pass an array of documents to the database. Now how will insert multiple document in single command:
Querying a document from a collection (Read):
To retrieve (Select) the inserted document, run the db.collection_name.find() 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.
Like in the relational database we can add primary key in the collection. In MongoDB default primary key is _id. Either we can send the primary key(_id) from the client or we can ignore. If we pass the primary key(_id) from the client, it will use the same as primary key, otherwise it will add a autogenerated key in the _id field.
Updating a document in a collection (Update)
Now that we have three documents in the "employee" collection, let's update one of those documents. We do this by using the "update" method of the collection object. We'll need to pass the "id" of the document that we want to update, as well as the new data. Let's change "Employee3" to "Employee".
Removing an entry from the collection (Delete)
Let us now consider the deleting an entry from a collection. In mongoDB the remove() method updating existing document. The db.[collection name].remove() accepts a query to remove the record. The description of the statement same as insert.