#Day40 - Getting Started with MongoDB: Installation and CRUD Operations

#Day40 - Getting Started with MongoDB: Installation and CRUD Operations

Learn MongoDB basics: Installation, MongoDB Shell, CRUD ops & more

Welcome to the 40th day of our blogging series!. "Getting Started with MongoDB: Installation and CRUD Operations" blog. In this blog, we will explore the basics of MongoDB, a leading NoSQL database. With the growing demand for scalable and flexible data storage solutions, MongoDB has become increasingly popular in the industry.

We will start with the installation of MongoDB Community Version on Windows, macOS, and Linux operating systems. After installation, we will dive into MongoDB Shell (mongo shell), which provides a way to interact with the MongoDB instance.

We will then cover the key concepts of MongoDB such as databases, collections, and CRUD (Create, Read, Update, Delete) operations. You will also learn about _id and ObjectId, which play an important role in managing documents in MongoDB.

By the end of this blog, you will have a solid understanding of the basics of MongoDB and be well equipped to perform common database operations using MongoDB. So, let's get started!

Installation of MongoDB Community Version

Introduction to MongoDB Community Version MongoDB Community Version is a free and open-source edition of MongoDB that provides access to the core functionality of the database. It is ideal for learning, developing and testing applications.

Downloading MongoDB Community Version from official website The MongoDB Community Version can be downloaded from the official MongoDB website. Download link: https://www.mongodb.com/download-center/community

Recommended Resources for Installing MongoDB. The official MongoDB website provides comprehensive guides for installation on different operating systems like Windows, macOS, and Linux. Windows installation guide: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/ macOS installation guide: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/ Linux installation guide: https://docs.mongodb.com/manual/administration/install-on-linux/ It's also important to note the system requirements for MongoDB before starting the installation process. These requirements can be found in the official documentation.

The installation process and prerequisites vary based on the operating system. It is recommended to follow the official guides mentioned in the previous section for a smooth and successful installation.

Introduction to MongoDB Shell (mongo shell) & MongoDB Compass

The MongoDB Shell, also known as mongo shell, which is a command line interface for interacting with MongoDB. This is a powerful tool for performing various operations in MongoDB, such as creating and managing databases, collections, and documents.

The MongoDB Shell provides a REPL (Read-Eval-Print Loop) environment, which allows you to quickly execute commands and view results in real-time. To connect to a MongoDB instance, simply type mongo in the terminal/command prompt and press enter. Once connected, you can perform a variety of tasks, such as creating databases, collections, and documents.

For those who prefer a more graphical interface, MongoDB also offers MongoDB Compass, a visual tool for exploring and managing your MongoDB data. With MongoDB Compass, you can easily visualize your data and perform common database operations, such as creating indexes, managing users, and executing queries.

In addition to the MongoDB Shell and MongoDB Compass, there's also mongoosh, a new MongoDB Shell alternative written in JavaScript and based on Node.js. This tool provides a modern and user-friendly interface, making it easier for developers to interact with MongoDB.

Database Operations

Introduction to Databases in MongoDB:

MongoDB uses databases to store collections of documents, which are similar to tables in a traditional relational database. Each database can have multiple collections, and each collection can have multiple documents.

Creating a database and its collections:

To create a database in MongoDB, you simply have to create a collection. If a database with the same name doesn't already exist, MongoDB will create one for you automatically. For example, to create a database named "testdb" and a collection named "testcol", you can run the following command in the MongoDB shell:

use testdb
db.createCollection("testcol")
Listing all databases and collections:

To list all the databases in your MongoDB instance, you can run the following command in the MongoDB shell:

show dbs

To list all collections in the current database, you can run the following command:

show collections
Switching between databases and collections:

To switch between databases, you can use the "use" command followed by the database name. For example, to switch to a database named "testdb", you can run the following command:

use testdb
Dropping a database and its collections:

To drop a database, you can use the "db.dropDatabase()" method. For example, to drop the "testdb" database, you can run the following command:

use testdb
db.dropDatabase()

Collection Operations

In MongoDB, a collection is a group of MongoDB Documents. Similar to how a table holds rows in a relational database, a collection holds documents in MongoDB. Collections are a way to group together similar data, and they provide a way to enforce structure on the documents within.

Introduction to Collections in MongoDB

Collections in MongoDB are dynamic, meaning that collections are not created until data is inserted into them. This differs from relational databases, where tables are created in advance and may have strict structures defined for them. In MongoDB, collections and the documents within them can have differing structures, but it is a best practice to keep the structure of documents within a single collection consistent.

Creating a Collection

To create a collection in MongoDB, you simply need to insert a document into it. The first time a document is inserted into a collection, the collection is automatically created. The following command creates a new collection named "users" and inserts a document into it:

db.users.insert({
    name: "John Doe",
    age: 30,
    location: "New York"
})
Listing all Collections in a database

To list all collections in a database, you can use the show collections command in the MongoDB shell. This will show you all collections in the current database:

> show collections
users
Dropping a Collection

To drop a collection, use the db.collection.drop() method in the MongoDB shell. This will delete the collection and all data within it. For example, to drop the "users" collection, you would run the following command:

> db.users.drop()
true
Importing and Exporting collections

To import or export collections in MongoDB, you can use the mongodump and mongorestore commands. mongodump exports collections from a MongoDB instance to a BSON file, and mongorestore imports collections from a BSON file into a MongoDB instance. For example, to export the "users" collection from a MongoDB instance running on localhost to a BSON file named users.bson, you would run the following command:

$ mongodump --collection users --db mydatabase --out /data/backup/

And to restore the "users" collection from the BSON file to a MongoDB instance running on localhost, you would run the following command:

$ mongorestore --collection users --db mydatabase /data/backup/users.bson

CRUD Document Operations on Single and Multiple Documents

In MongoDB, CRUD operations are used to manage data within a database. These operations include Creating, Reading, Updating, and Deleting documents from collections. In this section, we'll delve into the basics of CRUD operations on single and multiple documents.

CRUD stands for Create, Read, Update, and Delete, and these operations form the basis of database management in MongoDB. To perform CRUD operations, you'll need to use the MongoDB shell or a MongoDB driver. In this section, we'll focus on using the MongoDB shell to perform these operations.

Inserting Documents into a Collection

The first CRUD operation we'll discuss is inserting documents into a collection. To do this, we'll use the db.collection.insertOne() method to insert a single document, or the db.collection.insertMany() method to insert multiple documents. Here's an example of inserting a single document into a collection called "users":

db.employees.insertOne({
    name: "John Doe",
    age: 35,
    job: "Software Engineer"
})

And here's an example of inserting multiple documents:

db.users.insertMany([
   {
      name: "Jane Doe",
      age: 29,
      city: "Los Angeles"
   },
   {
      name: "Jim Smith",
      age: 40,
      city: "Miami"
   }
])

Retrieving Documents from a Collection

The next CRUD operation is retrieving documents from a collection. We can retrieve documents using the db.collection.find() method, which returns a cursor object. The cursor object can then be used to iterate over the documents, like this:

db.users.find().forEach(function(doc) {
   print(doc.name)
})

If you want to retrieve specific documents based on certain criteria, you can pass a query document to the find() method, like this:

db.users.find({city: "New York"}).forEach(function(doc) {
   print(doc.name)
})

Updating Documents in a Collection

To update documents in a collection, you can use the db.collection.updateOne() method to update a single document, or the db.collection.updateMany() method to update multiple documents. Here's an example of updating a single document:

db.users.updateOne(
   { name: "John Doe" },
   { $set: { city: "San Francisco" } }
)

And here's an example of updating multiple documents:

db.users.updateMany(
   { city: "New York" },
   { $set: { city: "San Francisco" } }
)

Deleting Documents from a Collection

The final CRUD operation is deleting documents from a collection. You can delete a single document using the db.collection.deleteOne() method, or multiple documents using the db.collection.deleteMany() method. Here's an example of deleting a single document:

db.users.deleteOne({ name: "John Doe" })

And here's an example of deleting multiple documents:

db.users.deleteMany({ city: "San Francisco" })

With these CRUD operations, you can easily manage documents within your MongoDB collections. Whether you need to insert, retrieve, update, or delete documents, MongoDB provides

_id/ObjectId in MongoDB

The id field is a unique identifier for each document stored in a MongoDB collection. It is used to index the document and to ensure that each document stored in the collection has a unique identifier. The id field is created automatically if not specified, and its default type is ObjectId.

The ObjectId is a 12-byte BSON type that is generated when a document is inserted into a MongoDB collection. The first four bytes represent the UNIX timestamp, the next three bytes are the machine identifier, the next two bytes are the process identifier, and the final three bytes are a counter, ensuring the uniqueness of the ObjectId.

To retrieve a document by ObjectId, use the findOne() method in the MongoDB shell, and pass the ObjectId as an argument. This is a useful method for quickly locating a specific document within a collection.

For example, to retrieve a document with ObjectId "5f23ddd741a62f49a2e1c11d", you would use the following command in the MongoDB shell:

db.collectionName.findOne({"_id": ObjectId("5f23ddd741a62f49a2e1c11d")})

the _id field and ObjectId are essential components of MongoDB that ensure unique identification of each document in a collection, enabling quick and efficient retrieval of documents.

Query and Projection Operators

MongoDB provides several query and projection operators to filter and display the data in a specific format. Query operators allow us to search the data based on certain conditions and projection operators allow us to select only the desired fields from the documents. In this section, we'll discuss both query and projection operators in detail.

Using Query Operators to Filter Data

Query operators are used to filter the data from the documents based on certain conditions. MongoDB provides several query operators such as $eq, $gt, $lt, $ne, $in, etc. to filter the data. For example, using the:

  • $eq: Matches documents where the specified field is equal to the specified value.

  • $gt: Matches documents where the specified field is greater than the specified value.

  • $lt: Matches documents where the specified field is less than the specified value.

  • $ne: Matches documents where the specified field is not equal to the specified value.

  • $in: Matches documents where the specified field is in the specified set of values.

Using Projection Operators to Display Specific Fields

Projection operators allow us to select only the desired fields from the documents. For example, we may only want to display the name and address fields from the documents, and ignore the rest of the fields. MongoDB provides several projection operators such as $include, $exclude, $slice, etc. to select the desired fields.

  • $include: This operator is used in projection to include only specific fields in the query result.

  • $exclude: This operator is used in projection to exclude specific fields from the query result.

  • $slice: This operator is used in projection to limit the number of elements in an array that is returned in the query result. It takes two arguments: the first specifies the starting position of the slice and the second specifies the number of elements to return.

Example

Let's consider a collection named "employees" with the following documents:

{
   "_id": ObjectId("5f44b04c58ea9c11d0c47b3f"),
   "name": "John Doe",
   "age": 32,
   "address": "123 Main St, Anytown USA 12345"
},
{
   "_id": ObjectId("5f44b04c58ea9c11d0c47b40"),
   "name": "Jane Doe",
   "age": 28,
   "address": "456 Elm St, Anytown USA 12345"
}

Using the query operator, we can filter the documents with age greater than 30 as follows:

db.employees.find({ age: { $gt: 30 } }).pretty()

This will display the following result:

{
   "_id": ObjectId("5f44b04c58ea9c11d0c47b3f"),
   "name": "John Doe",
   "address": "123 Main St, Anytown USA 12345"
},
{
   "_id": ObjectId("5f44b04c58ea9c11d0c47b40"),
   "name": "Jane Doe",
   "address": "456 Elm St, Anytown USA 12345"
}

Conclusion:

In this blog, we have covered the basics of MongoDB, including installation on different operating systems, using MongoDB shell and MongoDB Compass for interaction, and database operations such as creating databases, collections, and performing CRUD operations. With this knowledge, readers should now have a solid understanding of the basics of MongoDB and be well equipped to perform common database operations.

It is important to understand the basics of MongoDB, as it is a leading NoSQL database and its popularity is growing due to its scalability and flexibility. For further learning, the official MongoDB website provides comprehensive guides, tutorials, and resources.

I hope this blog has been helpful and informative. Thank you for reading! Please feel free to leave comments, ask questions, and share the blog with others.