Just like structured databases use Structured Query Language (SQL), MongoDB, the most popular NoSQL database uses MongoDB Query Language (MQL). MQL is rich and powerful, and fetches data easily even from documents with nested or complex structure, when queried correctly.
In this article, we will learn about some basic MQL queries for CRUD (Create, Read, Update and Delete) operations.
About MongoDB
As the world is turning digital, users are generating a lot of data, not all of which can be organized or structured in a standard format. However, all of the data needs to be persisted somewhere, to be analyzed by business analysts and data scientists to make strategic business decisions and improve overall business performance.
MongoDB is a document-based NoSQL database having a flexible schema and does not require a fixed format to store data. This helps store unstructured data like media files, sensor data and real-time transactional data. MongoDB stores data as documents into collections. There can be many collections, and as many documents into each collection, each document having its own set of fields.
Here is a quick mapping of how data stored in MongoDB vs an SQL database:
SQL database |
MongoDB |
Table |
Collection |
Row |
Document |
Column |
Field |
You can see the detailed mapping chart in the MongoDB manual.
Let us see an example of how a typical MongoDB document looks like:
|
Note that each document starts and ends with a curly brace ({}). Also, only the _id field is mandatory by default. The _id field is an unique internal identifier for each document and is generated by the system while inserting the document, if you do not specify a particular value. The above is a simple example of details of a user. MongoDB can easily handle more complex nested documents as well.
Here is another example to store objects:
{
_id: ObjectId("509a8fb2f3f5434bd2f983b2"),
login_id: "samy_123",
user_first_name: "Sam",
user_last_name: "Adams",
age: 23,
location: {
"lng" : 48.137154,
"lat" : 11.576124
},
address: {
"city" : "Munich",
"state" : "Bavaria",
"zipcode" : “80335”,
"countrycode" : “GER”,
"country" : "Germany"
}
}
Note that ‘address’ and ‘location’ are objects that further have fields to store the required information.
What is the MongoDB Query Language (MQL)?
To perform CRUD operations on a database, we need to query the database in a way that the database can understand. MongoDB has its own language called the MQL, to perform basic and advanced operations on the data. Apart from the basic CRUD operations, MongoDB provides powerful aggregation functions, and different operators, to filter, sort, group, and arrange data as per requirements, thereby improving the overall application performance. You can write the queries from shell or in the UI, via MongoDB Compass or MongoDB Atlas.
Basic CRUD operations
While going through the article, you may choose to parallelly work the queries. For this, you would either need to install mongo shell, MongoDB Compass, or connect to MongoDB Atlas UI. We are using mongo shell for all the commands below.
To connect to a MongoDB cluster on Atlas, use the following command from your shell:
|
To switch to or use a particular database, use the command:
use sample_training |
To view the collections present in the database, use:
show collections |
Read operation in MongoDB
To view the data present in the collection ‘grades’, use:
|
The find() method without any condition lists all the documents present in the collection. However, to find a specific record, we can place a condition, like:
|
This lists only those records that have ‘student_id’ field as 1.
To find record using multiple conditions, you can place multiple conditions using comma:
|
Insert operation in MongoDB
To insert a record, you can use the insertOne or insertMany command along with the data you want to insert. Note that MongoDB does not place any restrictions on the data you can add, so you have to make sure to add the right data in the right collections. Also, MongoDB also has an ‘insert’ method, which is now deprecated.
|
If the insert is successful, you will get a message as:
|
Update operation in MongoDB
Updating documents can be done in three ways in MongoDB:
- update() : updates one or many documents matching the criteria, based on the value set for the boolean parameter ‘multi’. If multi is false, the query updates only one record.
- updateOne(): updates the first document found with the matching criteria
- updateMany(): updates all the documents that match the specified criteria
Suppose we want to update the exam score to 35, in the document that we inserted above. The query is as follows:
|
Note that the scores field is an array, so we use the dot operator to access the fields. To update the value, we need to use the positional operator ($). If the document is updated successfully, you will get an acknowledgement:
|
Note the parameter upsertedCount. MongoDB uses an optional parameter known as ‘upsert’, the value of which can be a boolean (true/false). While writing the update query, if upsert is set to true, the document is inserted if it doesn’t exist.
For example, let’s try to update a document with _id as 10000 (which doesn’t exist), with upsert as true:
|
Here is the output:
|
The upsertedCount is 1, which means that MongoDB inserted a new record. We can check the same using our find() command, with the condition below:
|
You can view the newly created document:
|
Note that you cannot update the _id field, once created, as the _id field is immutable.
Delete operation in MongoDB
Similar to other operations, MongoDB provides deleteOne() and deleteMany() options.
The simple query to delete the document with _id: 1 is:
|
After successful delete, you will get an acknowledgement:
|
You can delete the second document (student_id: 10000) in the same way.
Conclusion
In this article, we have understood how we can perform basic CRUD operations using MQL. MongoDB can perform much more complex actions than these, like aggregations, which we will discuss in the upcoming posts.