Getting started with MongoDB: Concepts, Installation and Basic CRUD Operations

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.

Installation Steps

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

  1. Download the .msi installer from the MongoDB Community Server offical page
  2. Run the installer and follow the setup wizard.
  3. Make sure to select “Install MongoDB as a Service” and choose “Run service as Network Service user”.
  4. Keep the Data Directory and Log Directory as default location or if you want to a different location, then you can change it.
  5. Optionally you may choose to install MongoDB Compass GUI but we will be using MongoDB Shell in this article.
  6. Finish the installation
  7. Download the MongoDB Shell .msi installer from MongoDB Shell Download
  8. Install the MongoDB Shell by following the installation wizard.

For MacOS and Linux

We will be installing MongoDB in MacOS and Linux using .tgz Tarball and the process is almost the same

  1. 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.

  2. Extract the files from the downloaded archive.

    tar -zxvf <The Downloaded MongoDB File>.tgz
    
  3. 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:

    • Copy the binaries into a directory listed in your 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/
    
    • Create symbolic links to the binaries from a directory listed in your 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/
    
  4. Install the MongoDB Shell (mongosh)

    • Download the package with respect to the version you need from MongoDB Shell Download
    • Follow the above steps to uncompress the file and make the binaries in the /bin folder listed in the PATH environment variable.
  5. Alternatively add the path to the binaries of MongoDB Server and MongoDB Shell to the PATH variable via .bashrc file

    • Open .bashrc file present in the home directory
    sudo nano ~/.bashrc
    
    • At the end of the file add the following command replacing with actual path.
    export PATH=$PATH:<Path-To-The-MongoDB-Bin-Folder>:<Path-To-The-MongoDB-Shell-Bin-Folder>
    
    • Save the file and reload the .bashrc in the current shell by executing following command.
    source ~/.bashrc
    
  6. 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
    
  7. Run the MongoDB Server

    mongod --dbpath <path-to-mongodb-data-directory>/db --logpath <path-to-mongodb-data-directory>/logs/mongod.log --fork
    
  8. 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
    
  9. Start using MongoDB by running the mongosh with the following command without any arguments.

    mongosh
    

Basic CRUD Examples

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.

Creating/Inserting Document
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"]
        }
        ])
    

Querying the documents

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.

Updating Documents

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"})
    

Deleting Documents

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
  • Delete one document
    
    db.persons.deleteOne({ name : "Alex" })
    
  • Delete more than one documents
    
    db.persons.deleteMany({age : {$gt : 30}})
    
  • Delete all documents by passing an empty document {} to the deleteMany() method.
    
    db.persons.deleteMany({})
    

Summary

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