Date : May 4, 2025
MongoDB is a leading NoSQL database, often categorized as a document store and is one of the most popular NoSQL databases in the world, known for its scalability, flexibility, and ease of use. Whether you’re building a small app or a large-scale enterprise system, MongoDB provides a modern, document-based approach to storing data. It stores data in flexible, JSON-like BSON (Binary JSON) format, allowing for complex hierarchical structures. MongoDB is schema-less, meaning it doesn’t require predefined structures for its collections (akin to tables in relational databases). This makes it particularly useful for applications with evolving or varied data models like Document Model, Graph Model, Time Series Model, Geospatial Model and etc. MongoDB supports features like horizontal scaling, high availability, and robust querying capabilities. In this article, we’ll explore its key features, how to install it, and walk through simple CRUD (Create, Read, Update, Delete) operations with examples.
What is a Document Database ? A document in MongoDB is a data structure composed of field and value pairs and are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.
{
name : "Adam",
address : {
line1 : "324, Test Road",
landmark : "Demo Tower",
zipcode : 154-563
},
age : 32,
skills : [
"java",
"python",
"reactjs"
]
}
MongoDB stores documents in collections. Collections are analogous to tables in relational databases and the collections are stored in a database.
To follow along with this guide, we need the following packages. - MongoDB Community Server, the database server - MongoDB Shell, the CLI based client to interact with the server
For Windows
.msi
installer from the MongoDB Community Server offical page.msi
installer from MongoDB Shell DownloadFor MacOS and Linux
We will be installing MongoDB in MacOS and Linux using .tgz Tarball and the process is almost the same
Download the MongoDB Community .tgz tarball from Download Center. Please make sure to download the correct .tgz tarball with respect to the operatiing system and CPU architecture.
Extract the files from the downloaded archive.
tar -zxvf <The Downloaded MongoDB File>.tgz
Make sure the binaries are in a directory listed in your PATH
environment variable.
Since MongoDB binaries are in the bin/
directory of the tarball. You can either:
PATH
variable, such as /usr/local/bin (Update /path/to/the/mongodb-directory/ with your installation directory as appropriate)sudo cp /path/to/the/mongodb-directory/bin/* /usr/local/bin/
PATH
variable, such as /usr/local/bin (Update /path/to/the/mongodb-directory/ with your installation directory as appropriate):sudo ln -s /path/to/the/mongodb-directory/bin/* /usr/local/bin/
Install the MongoDB Shell (mongosh
)
/bin
folder listed in the PATH
environment variable.Alternatively add the path to the binaries of MongoDB Server and MongoDB Shell to the PATH
variable via .bashrc
file
.bashrc
file present in the home directorysudo nano ~/.bashrc
export PATH=$PATH:<Path-To-The-MongoDB-Bin-Folder>:<Path-To-The-MongoDB-Shell-Bin-Folder>
.bashrc
in the current shell by executing following command.source ~/.bashrc
Creating Data
and Log
directories where MongoDB server will store the data and logs.
sudo mkdir -p <path-to-mongodb-data-directory>/db
sudo mkdir -p <path-to-mongodb-data-directory>/logs
Run the MongoDB Server
mongod --dbpath <path-to-mongodb-data-directory>/db --logpath <path-to-mongodb-data-directory>/logs/mongod.log --fork
Check whether the MongoDB has started successfully by looking into the log file <path-to-mongodb-data-directory>/logs/mongod.log
for the following line
[initandlisten] waiting for connections on port 27017
Start using MongoDB by running the mongosh
with the following command without any arguments.
mongosh
We will be going through some basic CRUD examples. More detailed guide about create, read, update and delete operations will be discussed in seperate articles.
Method | Description |
---|---|
db.collection.insertOne() |
Inserts a single document into a collection |
db.collection.insertMany() |
Inserts multiple documents into a collection |
Inserting Single Document
db.persons.insertOne({
name : "Alex",
age : 30,
skills : ["java","Ruby", "Python"]
})
Inserting Multiple Documents
db.persons.insertMany([
{
name : "Ben",
age : 28,
skills : ["Selenium","Java", "Mockito"]
},
{
name : "Alice",
age : 25,
skills : ["Python","Pytorch", "AI", "Javascript"]
}
])
Method | Description |
---|---|
db.collection.find() |
Get all the documents that satisfies the query predicate |
db.collection.findOne() |
Get the first document that satisfies the query predicate |
A query predicate is a document {}
passed as a parameter to the above find()
and findOne()
methods.
In this article, we will only go through some basic query predicates to retrive the data. More in-depth about querying the data will described in a separate article.
To find all the documents in a collection, do not pass any parameters or pass an empty document to the find()
and findOne()
methods.
db.persons.find()
db.persons.find({})
Output
[
{
_id: ObjectId('681573c95f833e5f18b5f899'),
name: 'Alex',
age: 30,
skills: [ 'java', 'Ruby', 'Python' ]
},
{
_id: ObjectId('681573d35f833e5f18b5f89a'),
name: 'Ben',
age: 28,
skills: [ 'Selenium', 'Java', 'Mockito' ]
},
{
_id: ObjectId('681573d35f833e5f18b5f89b'),
name: 'Alice',
age: 25,
skills: [ 'Python', 'Pytorch', 'AI', 'Javascript' ]
}
]
Find the persons having age greater than 27
db.persons.find({ age : {$gt : 27} })
Output:
[
{
_id: ObjectId('681573c95f833e5f18b5f899'),
name: 'Alex',
age: 30,
skills: [ 'java', 'Ruby', 'Python' ]
},
{
_id: ObjectId('681573d35f833e5f18b5f89a'),
name: 'Ben',
age: 28,
skills: [ 'Selenium', 'Java', 'Mockito' ]
}
]
Please note, the field _id
has been created by MongoDB during document creation. This field contains unique value for each document and it has the type ObjectId
.
Method | Description |
---|---|
db.collection.updateOne() |
Update single document that satisfies the query predicate |
db.collection.updateMany() |
Update multiple document(s) that satisfies the query predicate |
db.collection.replaceOne() |
Replaces the entire content of a document except for the _id field |
Update a single document. (For example: Update the age
of Ben
to 31
)
db.persons.updateOne({name : "Ben"}, {$set : { age : 31 }})
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
The above query returns the output that it matched one document and modified one document. When you query the document using db.persons.find({name : "Ben"})
, you would see the updated output.
Update one or more documents. (For example: Update the city
to Rome
where age
is greater than 26
)
db.persons.updateMany({age : {$gt : 26}}, {$set : {city : "Rome"}})
Please note, the documents does not have the field city
during creation, so, in this case the updateMany
will add that field into the matching documents.
Replace the content of a document. In this case, the entire document is passed as the second document. (For example, replace the document having name Alex
)
db.persons.replaceOne({name : "Alex"}, {name : "Alex", hobbies : ["coding", "painting"], age : 32, country : "US"})
Method | Description |
---|---|
db.collection.deleteOne() |
Deletes the first document that satisfies the query predicate |
db.collection.deleteMany() |
Deletes all the documents that satisfies the query predicate |
db.persons.deleteOne({ name : "Alex" })
db.persons.deleteMany({age : {$gt : 30}})
{}
to the deleteMany()
method.
db.persons.deleteMany({})
In this guide, we get to know the basics of MongoDB including the features, installation steps and some simple CRUD examples. This will help understand how to get started with MongoDB server. More in-depth tutorials about the CRUD oprations and other advanced features will be published in the upcoming posts. Please stay tuned to this website for more interesting tech articles.
First published on : May 4, 2025