Insert, Update And Delete Document In MongoDB - Part Two

Introduction

Welcome back to the MongoDB article series - Part 2. In the previous article, we discussed the concept of MongoDB, including how to install MongoDB.  Now, in this article, we will discuss the basic structure of a MongoDB Database including its different data types. We will also learn how to insert, update, and delete data in a MongoDB database. Also, in this article, we will discuss how to create full-featured data storage that is scalable, flexible, and fast. If you want to read the previous articles of these series, then follow the links.

Data in MongoDB database is stored in form of documents. Code examples in this article shows how to create documents, insert, update, and delete documents in a MongoDB database. 

Understanding MongoDB

As per the discussion in the introduction articles, we have seen that the data in the MongoDB has a flexible schema. In MongoDB, we didn’t need to declare the new columns of a collection before inserting the data in this database just like the conventional RDBMS concept. So, there are some basic considerations we need to remember at the time of designing a schema in MongoDB.

  1. We need to design our schema as per our requirements.
  2. If we use two objects together then we need to combine these two objects as one object.
  3. We can perform joins at the time of writing data.
  4. We need to optimize our schema for most frequent data search
  5. We can perform the most complex data aggregation functions

What are the Documents?

A document is the basic unit of data in MongoDB which is basically equivalent to the row as per the concept of RDBMS systems. Actually, the document is the main heart of the MongoDB.

A document is an ordered set of keys with its associated data or values. Representation of these documents always changes in every programming language, but the basic structure of these types of documents is normally a map, hash, or dictionary. In the case of JavaScript, the document represents an object, just like below.

{“message” : “Hello, MongoDB”} 

The above document sample contains a key named “message” with a value of “Hello, MongoDB”. Most of the documents always contain a better complete structure that contains multiple and nested key-value pairs. Normally, a key within a document is mainly string type data. But, instead of that, the key always maintains some notable exceptions.

  • Key does not contain any null character. If any null character is used within a key it means it will denote the end of the key.
  • There are some special characters (like $ or . etc) which are mainly used for some special circumstances. These characters are basically reserved characters.

MongoDB is actually a type-sensitive and case-sensitive database. So, for this reason, the below two documents are not the same,

{“text”:”Hello”}  
{“Text”:”Hello”}  

The most important note about the document is that it does not allow any duplicate keys in a single document. For example, the below document is actually an invalid document in the case of MongoDB.

{“message” : “Hello, MongoDB”, “message” : “MongoDB is NoSQL DB”}  

What is the Collection?

In MongoDB, a collection can be considered as a Table as per the concept of RDBMS. Basically, the collection is a group of documents. Every collection in MongoDB always has dynamic schemas. This means that documents within a single collection can have any number of different elements or shapes. For example, below two documents can be stored within a single document in MongoDB.

{“message” : “Hello, MongoDB”} {“text”:”Hello”, “count”:10}  

As per the above example, both documents do not contain any common key. Also, these two documents also contain different types of values against the key value. So naturally, one question always arises in our mind  -- if it means we can store any type of data within a common collection with different types of document structure. Also, do we not require separate collections at all? So, as per the below points, we need to separate and store different structured documents in different collections.

  • Maintains the same collection for different types of documents 
  • It is must faster to obtain the list of collections rather than extract a list of types in a collection.
  • If we maintain separate collections for separate types of documents, then grouping a document on the basis of the same kind of elements is just easier to use.
  • Also, since MongoDB supports indexes, it is better to maintain separate collections for different types of documents so that we can apply indexes on the basis of document structure.
  • In MongoDB, every collection is known by its name. Collection names can be any string value or a UTF-8 string. But still, it contains some restrictions:
    • The Empty string (“”) is not a valid collection name.
    • Collection names cannot contain a null character.
    • Also, we cannot create any collection name starting with the system keyword. 
    • The collection name which is created by the user does not contain any special characters like ($) in the name.

Data Types of MongoDB

MongoDB actually supports a wide range of data types as values in documents. Actually, MongoDB documents are always thought of as  JSON-like data which is a JavaScript object. JSON is basically a simple representation of data. The advantage of JSON is it helps to  understand, parse and remember. JSON can accept only null, Boolean, numeric, string, array and object types of data. The below list are the available data types in the MongoDB.

Data Types Descriptions
String It is most the commonly used data type. A string must be UTF-8 valid in MongoDB
Integer It is used to store numeric values. It may be either 32 bit or 64 bits.
Boolean It is used to store Boolean data types. It's valued either true or false.
Double It is used to store floating-point values.
Arrays These data types are used to store a list of multiple values in a single key
Objects This data type is used to store embedded data
Null It is used to store null data
Date This data type is used to store the current date or time value in UNIX time format.


MongoDB Shell

To interact with MongoDB, we can use the MongoDB Shell which is an interactive JavaScript interface for the MongoDB. We can use the Mongo shell to query and insert or update or delete any document from the MongoDB Collections. To start the MongoDB shell, we need to open a command prompt and then go to the root directory when MongoDB installed. Suppose that, I have installed the MongoDB in the drive D with a Folder Name MongoDB 4.0. So, the command prompt position is as below image.

Insert, Update And Delete Document in MongoDB 

Now, to start the MongoDB, type the below commands from that location.

Insert, Update And Delete Document in MongoDB

Create and Drop Database in MongoDB

In MongoDB, the first basic steps are to create a database. The database is used to store all the collections. In MongoDB, there is no command available to create a database. Actually, we did not need to create a database, MongoDB creates a database automatically by itself when we want to save any data within a collection. Actually, we don’t need to mention what we want to create, it automatically performs that task.

We can use the below command to check if that database is existing or not. If there is no database exist, then it will create a database. If the database exists, then it will return the existing database.

> use sampledb

If we want to check which database we currently selected, then use the below command,

> db

If we want to check database list, then we can use the below commands,

> show dbs

Insert, Update And Delete Document in MongoDB

If we want to drop a database, then we need to use the drop database command as below, 

> db.dropDatabase()

Create and Drop Collections in MongoDB

After creating a MongoDB Database, it’s time to create a collection in the existing MongoDB Database. So, to create a new collection in the database, we need to use db.createCollection(name, option) commands. This method takes two parameters.

  1. name parameter basically takes a string value which represents the collection name
  2. option parameter takes a document object which specifies the memory size including indexing options. This parameter is optional. This parameter takes four types of options, 
Field Type Description
capped Boolean If the value is true, then the collection will act as a capped collection. The capped collection is basically a fixed-size collection which automatically replaces the old values with the new values when size exceed. The default value is false.
autoIndexId Boolean If it is true, then automatically creates an index on the fields of _id. The default value is false.
size Number It is required when the capped field value is true. We need to provide the value in number to mention the maximum size in bytes for the capped collections.
max Number It is required when the capped field value is true. It mentions the maximum number of documents within a capped collection.

So, the simplest command for creating a collection is as below,

Insert, Update And Delete Document in MongoDB 

Also, we can create the collections using both the parameters, which means name and options like below –

Insert, Update And Delete Document in MongoDB 

So, if we need to drop the collections then we need to use drop() command as below.

> db.Employee.drop()

Insert Single Document

Now, in the previous section of this article, we created a database and collections. Now, it’s time to insert records into the collections. So, Insert is the basic command to insert any documents within the collections. This command inserts a single document within the collections. This command also adds “_id” command within the document if it is not mentioned in the document objects.

Insert, Update And Delete Document in MongoDB

Also, the Insert() command can insert multiple records at a time. For inserting bulk data using insert command, the syntax is as below,

Insert, Update And Delete Document in MongoDB

Now, after successful insertion of data, we need to fetch the data to see whether it is really inserted into the collections or not. For that, the user needs to use the find() command.

Insert, Update And Delete Document in MongoDB

This command also shows that MongoDB automatically inserts the “_id” column into the collections. 

Delete Document

Now, we have inserted data into the collection. Now, if we want to delete this data then we need to use the below commands,

db.Employee.remove()

This command will remove all the documents within the Employee Collections. This command does not remove the collections. It only deletes all the documents of the collections and makes the collections empty. This remove() accepts an optional parameter called query document which is normally used to specify any specific criteria for the remove the documents. If the query value is given, then only those documents will be deleted which are matched with a query expression.

db.Employee.remove(“Department”:”Accounts”)

So, the above command removes only those employee details whose department is Accounts. One more thing we need to remember is that once we remove any document, it is deleted forever. There is no way to undo the remove or recover the deleted documents.

Document Update

So, after inserting a document into the database, these documents can be changed using the Update() method. Update() method takes two parameters - a query document that specifies the criteria or condition by which a system identifies which document needs to be updated and the second one is an updated document, which needs to be replaced with the existing document. This update operation is an automatic process. That means if two simultaneous updates are fired in the server at the same time, then whichever one reaches the server first will be applied first and then the next one will be applied.

Insert, Update And Delete Document in MongoDB

Conclusion

So, in this article, we discussed the following topics,

  • How to Create Database in MongoDB
  • How to Create Collections in MongoDB
  • How to Insert Documents (both Single Document and Multiple Documents)
  • How to Delete Documents
  • How to Drop Collections
  • How to Update Existing Data on the Basis of Any Condition
  • How to Drop Database

I hope this article will help you. Any feedback or queries related to this article are most welcome. If anybody has a query related to this article, then ask me. 

Next article >> Query on Stored Data in MongoDB Part 3 


Similar Articles