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 and also, we will discuss how to insert, update, and delete the data within 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.
- Introduction to MongoDB - Part One: https://onlinessolution.blogspot.com/2019/09/introduction-to-mongodb-part-one.html
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 the MongoDB.
- We need to design our schema as per our requirements.
- If we use two objects together then we need to combine these two objects as one object.
- We can perform joins at the time of writing data.
- We need to optimize our schema for most frequent data search
- We can perform 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 type 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 which contain multiple and nested key-value pairs. Normally, a key within a document is mainly string type data. But, instead of that, 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 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 the 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 means we can store any type of data within a common collection with different types of document structure. Also, do we not require separate collection 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 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 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 the 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 | This data types are used to store a list or 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.
Now, to start the MongoDB, type the below commands from that location.
Create and Drop Database
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
> use sampledb
If we want to check which database we currently selected, then use the below command,
> db
> db
If we want to check database list, then we can use the below commands,
> show dbs
> show dbs
If we want to drop a database, then we need to use the drop database command as below,
> db.dropDatabase()
> db.dropDatabase()
Create and Drop Collections
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.
- name parameter basically takes a string value which represents the collection name
- 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,
Also, we can create the collections using both the parameters, which means name and options like below –
So, if we need to drop the collections then we need to use drop() command as below.
> db.Employee.drop()
> 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.
Also, the Insert() command can insert multiple records at a time. For inserting bulk data using insert command, the syntax is as below,
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.
This command also shows that MongoDB automatically inserts the “_id” column into the collections.
Delete Document
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()
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”)
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 document can be changed using the Update() method. Update() method takes two parameters - a query document which 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.Document Update
No comments:
Post a Comment