Table of contents
- What is MongoDB?
- Basic Concepts
- Features
- Installation
- Mongosh
- Basic Operations in MongoDB
- Query Language
- Querying Documents
- Updating Documents
- Deleting Documents
- Filtering
- Projection
- Show Available Databases
- Switch to a Database
- Show Collections in a Database
- Create a Collection
- Insert Documents
- Find Documents
- Update Documents
- Delete Documents
- Count Documents
- Query with Operators
- Indexes
- Aggregation
- Export and Import Data
- Conclusion
MongoDB is a popular and powerful NoSQL database that stores data in a document-oriented manner. It allows you to store and retrieve data in various formats, including JSON, CSV, and even binary data. MongoDB comes with many features and capabilities, such as being able to scale horizontally to handle large amounts of data, support for geospatial searches, and replication functionality for data redundancy.
In this beginner's guide to MongoDB, we will discuss the basics of MongoDB, how to install it, and some basic operations that you can perform using the MongoDB shell.
What is MongoDB?
MongoDB is a document-oriented NoSQL database management system. What this means is that data is stored in the form of documents, which can be nested and contain arrays of data elements. The data in MongoDB is stored in BSON format (Binary JSON format), which is a binary representation of JSON documents.
MongoDB is schema-less, meaning that it doesn't enforce a rigid structure on the data that you store, which allows for flexibility in your data modeling. This structure allows you to work with data in a more natural and intuitive way and helps to create more efficient queries.
Basic Concepts
Document-Oriented
MongoDB is document-oriented, which means it is a type of NoSQL database that stores data as documents. Documents can be thought of as the equivalent of rows in a traditional relational database. However, in MongoDB, each document can have its own structure and data schema.
Collection
A collection in MongoDB is a group of related documents that share a common index. It can be considered equivalent to the concept of tables in traditional relational databases.
Document
A document in MongoDB is a basic unit of data, which is composed of field-value pairs. Each field represents a piece of data stored within the document. MongoDB supports dynamic schema, which means the fields in the document do not need to be defined before the document is created.
Aggregation Pipeline
MongoDB provides an aggregation framework that allows developers to process data by chaining multiple stages together to form a pipeline. Each stage performs its own operation on the input and passes the result to the next stage in the pipeline.
Features
MongoDB offers a number of features that set it apart from traditional relational databases, including:
Schemaless
As mentioned earlier, MongoDB supports dynamic schema. This means the fields in the document do not need to be defined before the document is created.
Scalability
MongoDB is designed to scale horizontally, which allows you to add more nodes to the database cluster to increase capacity and performance. This is achieved by distributing the load across all nodes in the cluster.
Flexibility
MongoDB supports several types of data, such as text, dates, and numbers. It also has the ability to store and index geographic data, making it a popular choice for implementing location-based services.
High Performance
MongoDB uses memory-mapped files, which allows for faster reads and writes compared to traditional relational databases. It also includes a built-in caching system that minimizes the number of reads from disk.
Aggregation Framework
MongoDB includes a powerful aggregation framework that allows developers to perform complex queries and data manipulations. The framework allows users to chain together multiple stages to create a data processing pipeline.
JSON-based Querying
MongoDB uses a JSON-based query language that is both powerful and easy to learn. The query language supports a wide range of operators and functions, allowing developers to perform complex queries with ease.
GridFS
MongoDB provides GridFS, a system for storing and retrieving large files, such as images or videos. GridFS stores files in multiple chunks, which allows for efficient retrieval of only the parts of the file that are needed.
Installation
Now that you have an understanding of MongoDB's basic concepts and features, let's go through a step-by-step installation process for MongoDB on Windows.
Step 1: Download and Install
Download the latest version of MongoDB from the official MongoDB website: https://www.mongodb.com/download-center/community
Once the download is complete, double-click on the executable to begin the installation process. Follow the prompts in the installation wizard, which will guide you through the installation process.
Step 2: Start MongoDB
After the installation is complete, navigate to the MongoDB installation directory within the command prompt using:
cd C:\Program Files\MongoDB\Server\{version}\bin
Note: Make sure to replace {version}
with the version number of the installed MongoDB.
Next, run the mongod.exe file, which will start the MongoDB server:
mongod.exe
Alternatively, you can specify the data directory for storing the data files from the command line:
mongod.exe --dbpath "C:\data\db"
Step 3: Connect to MongoDB
Finally, connect to the MongoDB server using the mongo.exe command, which will open up the MongoDB console:
mongo.exe
Once you have connected to the console, you can create or query databases and collections.
Mongosh
Mongosh is an interactive MongoDB shell that provides a modern command-line interface for working with MongoDB. It's designed to be more user-friendly and intuitive than the MongoDB shell, and provides many features that make working with MongoDB easier.
Mongosh can be installed on Windows, Mac, and Linux, and supports a wide range of commands and options. Some of the key features of Mongosh include:
Autocompletion
Syntax highlighting
Improved error messages
Tabbed output
Command history
Help documentation
To install Mongosh, follow these steps:
Visit the official Mongosh website - mongosh.com - and click the 'Download' button.
Choose the version of Mongosh that corresponds to your operating system, and download the installer.
Run the installer and follow the prompts to install Mongosh on your machine.
Once installed, you can open Mongosh by running the mongosh
command in your terminal. This will launch the interactive shell, where you can start entering commands and working with your MongoDB database.
Mongosh is a powerful tool for working with MongoDB, and provides many features that can help to streamline your workflow and make your development process more efficient.
Basic Operations in MongoDB
Now that you have MongoDB installed, you can start working with it using the MongoDB shell. We will now show you some basic operations in MongoDB that you can perform using the MongoDB shell.
Creating a Database
To create a database in MongoDB, run the "use" command in the shell followed by the name of the database you want to create. For example, the following command creates a database named "mydb".
use mydb
Creating a Collection
A collection is a group of related documents in MongoDB. To create a collection in MongoDB, you can run the following command:
db.createCollection("mycollection")
Inserting Documents
To insert a document into a collection, use the "insertOne" or "insertMany" method of the collection object.
For example, to insert a single document with name and age fields, run the following command:
db.mycollection.insertOne({ name: "John Doe", age: 30 })
To insert multiple documents, use the "insertMany" method, like this:
db.mycollection.insertMany([{ name: "John Doe", age: 30 }, { name: "Jane Doe", age: 25 }])
Query Language
MongoDB uses a JSON-based query language that includes several operators for querying and manipulating data.
Querying Documents
To retrieve documents from a collection, use the "find" method of the collection object.
For example, to retrieve all documents from the "mycollection" collection, run the following command:
db.mycollection.find()To filter the results, you can pass a query object to the "find" method. For example, to retrieve documents where the "age" field is greater than 25, run the following command:
db.mycollection.find({ age: { $gt: 25 } })
Updating Documents
To update a document in a collection, use the "updateOne" or "updateMany" method of the collection object.
For example, to update a document with name "John Doe" and set the age to 32, run the following command:
db.mycollection.updateOne({ name: "John Doe" }, { $set: { age: 32 } })
Deleting Documents
To delete a document from a collection, use the "deleteOne" or "deleteMany" method of the collection object.
For example, to delete the document with name "John Doe", run the following command:
db.mycollection.deleteOne({ name: "John Doe" })
Filtering
Documents can be filtered based on multiple criteria using the same find() method. The following example demonstrates how to filter by multiple fields:
db.collection.find({ field1: "value1", field2: "value2" })
Projection
Projection can be used to retrieve only specific fields from a document. This can help to reduce the amount of data returned by a query and improve performance. The following example demonstrates how to use projection:
db.collection.find({ field: "value" }, { _id: 0, field1: 1 })
In this example, the query retrieves documents where the field matches the specified value but only returns the field1 field and suppresses the _id field.
Show Available Databases
To show the available databases on the MongoDB server, use the show dbs
command. This will display a list of all the databases on the server.
> show dbs
admin 0.000GB
local 0.000GB
test 0.000GB
Switch to a Database
To switch to a specific database, use the use
command, followed by the name of the database.
> use test
switched to db test
Show Collections in a Database
To show the collections in the current database, use the show collections
command. This will display a list of all the collections in the database.
> show collections
Create a Collection
To create a new collection, use the db.createCollection()
command, followed by the name of the collection.
> db.createCollection("users")
{ "ok" : 1 }
Insert Documents
To insert a document into a collection, use the db.collection.insert()
command, followed by the document to insert.
> db.users.insert({ name: "John Doe", age: 35 })
WriteResult({ "nInserted" : 1 })
Find Documents
To find documents in a collection, use the db.collection.find()
command, followed by the query to search for.
> db.users.find({ name: "John Doe" })
{ "_id" : ObjectId("5f923be18ee1b183f3ddef59"), "name" : "John Doe", "age" : 35 }
Update Documents
To update a document in a collection, use the db.collection.update()
command, followed by the query to search for and the changes to make.
> db.users.update({ name: "John Doe" }, { $set: { age: 36 } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Delete Documents
To delete a document from a collection, use the db.collection.remove()
command, followed by the query to search for.
> db.users.remove({ name: "John Doe" })
WriteResult({ "nRemoved" : 1 })
Count Documents
To count the number of documents in a collection, use the db.collection.count()
command.
> db.users.count()
0
Query with Operators
MongoDB provides various query operators that can be used to filter documents based on different criteria. Here are some examples:
$gt
: Greater than operator> db.users.find({ age: { $gt: 30 } })
$lt
: Less than operator> db.users.find({ age: { $lt: 40 } })
$in
: In operator> db.users.find({ name: { $in: ["John Doe", "Jane Doe"] } })
$regex
: Regular expression operator> db.users.find({ name: { $regex: /^J/ } })
Indexes
Indexes in MongoDB can be used to improve query performance. Here are some commands related to indexes:
db.collection.createIndex()
: Creates an index on a collection.> db.users.createIndex({ name: 1 })
db.collection.getIndexes()
: Shows all the indexes on a collection.> db.users.getIndexes()
db.collection.dropIndex()
: Deletes an index from a collection.> db.users.dropIndex("name_1")
Aggregation
Aggregation in MongoDB allows you to analyze and process data using a set of pipeline stages. Here are some aggregation commands:
db.collection.aggregate()
: Performs aggregation on a collection.> db.users.aggregate([ { $group: { _id: "$age", count: { $sum: 1 } } } ])
db.collection.distinct()
: Returns an array of distinct values for a field.> db.users.distinct("age")
Export and Import Data
You can export and import data in MongoDB using the following commands:
mongoexport
: Exports data from a collection to a file.> mongoexport --db test --collection users --type csv --fields name,age --out users.csv
mongoimport
: Imports data from a file to a collection.> mongoimport --db test --collection users --type csv --headerline --file users.c
Conclusion
In this article, I've introduced some of the basic MongoDB commands that you should be familiar with when working with MongoDB. These commands will allow you to perform common operations like adding, modifying, and deleting data, as well as querying and counting documents. With this knowledge, you can start building powerful and flexible applications using MongoDB.