Introduction to MongoDB: It is NoSQL Database beginners

MongoDB is an example of the NoSQL database that enables the user to store data and understand from the database with greater efficiency. Unlike contemporary models such as relational database models that store data in tables with rows and columns, MongoDB utilizes the document-based model in which data is stored in documents in the form of JSON-like. This makes it suitable for use with data that may not have a well defined structure such as the data set that is normally encountered in web applications today that is semi structured at best.

In this part of the tutorial, we explain some of the fundamental concepts of MongoDB such as the structure of the data and how to do some simple operations via the command line using a MongoDB shell.

What is MongoDB?

MongoDB is a type of NoSQL database that has been developed by MongoDB, Inc. This database is uniquely built for scalability and high availability together with the best performance. It is also used for web applications, for real time data analytics, for managing content and much more.

Key features of MongoDB:
1. Document-Oriented: MongoDB stores data in structures that are called BSON (Binary JSON), which can be compared to a dédicated type of documents with a JSON-like structure. This let you to store the array or nested object into a single record, which is helpful in many circumstances.
2. Schema-less: MongoDB is schema-less and this is as if all the documents in a given collection do not need to have properties in them. Consequently, there can be more versatile and dynamic structures of storing data.
3. Scalability: MongoDB also supports a horizontal scalability through the process of sharding; this is where the data is split across many servers or clusters.
4. High Availability: MongoDB recognizes replica sets that is a set of MongoDB servers that have the same data and act as backups and failovers.
5. Rich Query Language: MongoDB uses an efficient language when it comes to discarding, sorting, selecting and combination of data. It also helps in having index data that may help to enhance the kind of query that can be performed on it.

Setting Up MongoDB

As a prerequisite for MongoDB to be useful it needs to be installed on the system first. MongoDB can be installed on different operating systems such as Windows, MAC OS, as well as Linux. You can download and install MongoDB from the [official MongoDB website](https:Because this is a recent release due to the MongoDB 2.0 release (see www. mongodb. com/try/download/community).

Alternatively, you can use a cloud-hosted MongoDB service like [MongoDB Atlas](https:One such database is MongoDB, which has a simple offering to help users get started at no charge at their cloud platform (MongoDB Cloud at www. mongodb. com/cloud/atlas).

MongoDB Basics

1. MongoDB Data Model

In MongoDB, data is stored in collections these being similar to tables in relational databases. Every collection consists of several documents, and each document is an object in the form of key-to-value association.

Example of a MongoDB Document:Example of a MongoDB Document:

{
“_id”: ObjectId(“60c72b2f9f1b2c3a2e8b4567”),
“name”: “John Doe”,
“email”: “johndoe@example. com”,
“age”: 30,
“address”: {
“street”: “123 Main St”,
“city”: “New York”,
“state”: “NY”,
“zip”: “10001”
},
“hobbies”: [“reading”, “traveling”, “coding”]
}

Key points:
_id: Every document has its identifier which is denoted by `_id`. If not stated, MongoDB will create one by its default.
Embedded Documents: The `address’ field is an instance of the embedded document Another feature of MongoDB which is usually used when working with nested objects.
Arrays: The `hobbies’ is listed as an array of values this is good indication that MongoDB is capable of storing more than one value within a single cell.

2. MongoDB Shell

MongoDB shell is the interface which is used for querying and manipulating the MongoDB databases and it uses ‘JavaScript’. It can also be used for manage databases, create, read, update and delete data and to execute a queries.

To start the MongoDB shell, open your terminal and run:To start the MongoDB shell, open your terminal and run:

mongo

This will link you to the MongoDB server by default which is set to run on `localhost` with the port 27017.

3. In this case, creating a database and collection is necessary in order to successfully accomplish the research objectives.

In MongoDB, databases can be created on the fly what means that one does not need to define them ahead as it is done with other databases. When you begin to query a new database, MongoDB creates this database when you begin to enter data into it.

Creating a Database:

use my database

This command enables one to change to a database that is referred to as `mydatabase `. If there is no database available then it will form one provided it has permission to do so.

Creating a Collection:

New collections are also formed dynamically when a document is inserted to the collection. You do not actually need to create a collection out of it in some way, or try and shape it in a way that makes its relationships obvious.

db. users. insertOne({
“name”: “Alice”,
“email”: “alice@example. com”,
“age”: 28
})

This command uses in put method to insert a document into the `users’ collection. If there are no such collection as `users` it will be created automatically.

4. Basic CRUD Operations

Create (Insert):

Insert a single document into a collection:Insert a single document into a collection:

db. users. insertOne({
“name”: “Bob”,
“email”: “bob@example. com”,
“age”: 32
})

Insert multiple documents into a collection:Insert multiple documents into a collection:

db. users. insertMany([
{“name”: {“name”: “charlie”, “email”:”charlie@example.com” “age”: 25},
{“name”: > { “first_name”:”Dave”, “email”: “dave@example. com”, “age”: 29}
])

Read (Find):

Find all documents in a collection:Find all documents in a collection:

db. users. find()

Find a document with a specific criterion:Find a document with a specific criterion:

db. users. findOne({“name”: “Alice”})

Find documents with a specific age:Find documents with a specific age:

db. users. find({“age”: {$gte: 30}})

Update:

Update a single document:

db. users. updateOne({“name”: >MongoDB structure: $update( [‘users’, {$push: {friends: “Bob”}}, {$set: {age: 33}}] )

Update multiple documents:

db. users. updateMany({“age”: {$lt: 30}, {$set: {“status”: “active”}}

In the example above:
`updateOne` affects the first document that meets the condition (`name` is equal to `Bob`) and sets the value of the `age` field to `33`.
`updateMany` updates all documents where `age` is less than `30`, set a new value for the new ‘status’ field to ‘active’.

Delete:

Delete a single document:

db. users. deleteOne({“name”: “Charlie”})

Delete multiple documents:

db. users. deleteMany({“age”: {$gte: 30}})

In these commands:
The `deleteOne` function deletes the first document that satisfies the condition given in the argument, which are `name` as `”Charlie”`.
`deleteMany` deletes all documents with `age >= 30`.

Indexing in MongoDB

MongoDB uses indexes in order to enhance search operations. If no indexes are available, MongoDB has to perform collection scan which means that all the documents in the respective collection will be scanned in order to retrieve the documents matching the query.

Creating an Index:

To create an index on a field, you can use the `createIndex` method:To create an index on a field, you can use the `createIndex` method:

db. users. createIndex({“email”: 1})

This provides an ascending index on the emails field. You can also create multi-column indexes (when an index is created on multiple fields) or go for other features such as unique indexes.

Aggregation in MongoDB

Aggregation operations operate on data and input records and produce a computed result. It is usually employed where advanced computations on data are required like getting averages or even for preparing of reports.

Basic Aggregation Example:

db. users. aggregate([
{$match: {“age”: {$gte: 25}}},
{$group: This is the grouping of documents by ‘_id’ field, calculation of average age by ‘averageAge’ field and using ‘$avg’ operator.
])

In this example:
Lit. `$match` restricts the documents to those documents only where ‘age’ is more than equals to ‘25’.
The `$group` operation categorizes the documents by `status` and then the `$avgAge` determines the average age of the documents within each group.

Conclusion

MongoDB is a Non-Relational database that offers adaptability, extensibility and efficiency of web applications. Some of its features include document-oriented model, schema-less design, and rich query language that makes it preferred by developers who are developing application that handle unstructured / semi-structured data.

In this introduction, through introduction, you have been introduced to how to use MongoDB, how to create a database and a collection, insert, select, update, delete, and index, and use the aggregation function. With this setting, you are prepared to discover even more of MongoDB, for instance, sharding, replication, application with complex forms of data.

Because of its flexibility as well as simplicity, MongoDB is a perfect fit for developing apps with easy scalability for everyone ranging from a single developer on a project or a large scale enterprise system.

Leave a Comment