Getting Started with MongoDB: Installation and Basic Commands

    Getting Started with MongoDB: Installation and Basic Commands

    In this blog, we will learn how to install MongoDB, perform basic CRUD operations, create indexes, and even write simple aggregation pipelines.

    default profile

    Anuj Kumar Sharma

    September 13, 2025

    6 min read

    Welcome to the first part of my four-part series on building an e-commerce order management system with Spring Data MongoDB! If you're new to MongoDB or looking to harness its power for flexible, scalable applications, you're in the right place.

    If you've been working with traditional SQL databases and hearing all the buzz about NoSQL, you're probably curious about what makes MongoDB so special. Well, you're in the right place! This is the first post in our four-part series where I will cover MongoDB basics all the way to building sophisticated Spring Boot applications with complex queries.

    This article is part of our comprehensive 4-part MongoDB with Spring Boot series.

    Part 1 (Current): Getting Started with MongoDB: Installation and Basic Commands

    Part 2: MongoDB with Spring Boot using Spring-Data-MongoDB

    Part 3: MongoDB Relationships in Spring Boot

    Part 4: Advanced MongoDB Queries: Mastering Criteria API and MongoTemplate

    Why MongoDB?#

    Before we dive into installation and commands, let me ask you a simple question - why should you care about MongoDB? In today's world of microservices and cloud-native applications, MongoDB offers something that traditional databases struggle with: flexibility and scalability. Unlike rigid table structures, MongoDB stores data in flexible, JSON-like documents. This means you can store complex nested data without the headache of multiple JOIN operations.

    Real-world data is messy, hierarchical, and constantly evolving. MongoDB embraces this reality.

    Setting Up MongoDB on Your Machine#

    Let's get MongoDB up and running on your system. The installation process varies slightly depending on your operating system.

    If you don’t like Docker or you have not used it yet, let me tell you this is the best way to run services in an isolated environemnt inside your computer. You don’t need to worry about complicated setup, system permissions and configuration, and cleanup when you want to unistall it. Docker simplifies setting up MongoDB. Here's how to get started:

    1. Install Docker: Ensure Docker is installed (e.g., Docker Desktop for Windows/Mac or Docker on Linux).
    2. Pull MongoDB Image: Run the following command to download MongoDB 7.0:
    docker pull mongo:8.0

    Run MongoDB Container: Start a MongoDB instance with a root user for authentication:

    This maps port 27017 (MongoDB's default) to your host and sets up an admin user.

    docker run -d --name mongodb -p 27017:27017 \\ -e MONGO_INITDB_ROOT_USERNAME=admin \\ -e MONGO_INITDB_ROOT_PASSWORD=password \\ mongo:8.0
    1. Verify: Check if the container is running:
    docker ps

    With MongoDB running, connect using mongosh, MongoDB's shell:

    docker exec -it mongodb mongosh -u admin -p password

    This opens the MongoDB shell. If you installed directly, run mongosh locally.

    Installing on Windows#

    For Windows users, head over to the MongoDB download center and grab the MSI installer. The installation wizard will guide you through the process. Make sure to:

    1. Choose "Complete" installation
    2. Install MongoDB as a Windows Service (this ensures MongoDB starts automatically)
    3. Include MongoDB Compass (the GUI tool) in your installation

    Installing on macOS#

    Mac users have it easy with Homebrew. Simply run:

    brew tap mongodb/brew brew install mongodb-community

    To start MongoDB as a service:

    brew services start mongodb-community

    To connect with your MongoDB database, open your terminal and type mongosh (or mongo for older versions) to enter the MongoDB shell. You'll see something like:

    Current Mongosh Log ID: 65f3d4c5... Connecting to: mongodb://127.0.0.1:27017 Using MongoDB: 8.0.0 Using Mongosh: 2.1.5

    Congratulations! You're now connected to your MongoDB instance. Let's explore some essential commands that you'll use daily.

    MongoDB Commands#

    Now, let's explore MongoDB's core commands to manage databases and collections for our e-commerce system. We'll use a database named ecommerce to store our users, orders, and products.

    1. Database Operations#

    • List Databases: See all databases:
    show dbs
    • Switch/Create Database: Use ecommerce (created on first write):
    use ecommerce

    2. Collection Operations#

    Collections are like tables but hold JSON-like documents. Let's create an orders collection.

    Insert a Document:

    This adds a single order document.

    db.orders.insertOne({ _id: "order123", status: "pending", quantity: 2, totalPrice: 199.98, address: { city: "Delhi", state: "Delhi", zipCode: "110001" } })
    • List Collections:
    show collections

    3. Querying Documents#

    • Find All Orders:
    db.orders.find() db.orders.find().pretty()

    Filter by City:

    Queries the embedded address field.

    db.orders.find({ "address.city": "Delhi" })
    • Find One Document:
    db.orders.findOne({ status: "pending" })

    4. Updating Documents#

    • Update Status:
    db.orders.updateOne( { _id: "order123" }, { $set: { status: "shipped", updatedAt: new Date() } } )
    • Update Multiple:
    db.orders.updateMany( { "address.city": "Delhi" }, { $set: { status: "processing" } } )

    5. Deleting Documents#

    db.orders.deleteOne({ _id: "order123" })
    db.orders.deleteMany({ status: "cancelled" })

    6. Indexing for Performance#

    Indexes speed up queries, crucial for fields like address.city in our e-commerce app.

    • Create Index:
    db.orders.createIndex({ "address.city": 1 })
    • List Indexes:
    db.orders.getIndexes()

    7. Inserting Multiple Documents#

    Add more orders to simulate real data:

    db.orders.insertMany([ { _id: "order456", status: "shipped", quantity: 1, totalPrice: 999.99, address: { city: "Mumbai", state: "Maharashtra" } }, { _id: "order789", status: "pending", quantity: 3, totalPrice: 149.97, address: { city: "Delhi", state: "Delhi" } } ])

    8. Useful Administrative Commands#

    Here are some commands you'll find handy:

    Check collection statistics:

    db.products.stats()

    See the current database:

    db

    Drop a collection (careful with this one!):

    db.products.drop()

    Drop the entire database (even more careful!):

    db.dropDatabase()

    MongoDB Compass#

    While the command line is powerful, sometimes you want a visual interface. MongoDB Compass (which you installed earlier) provides a GUI for:

    • Viewing and editing documents
    • Building queries visually
    • Viewing real-time server statistics

    Launch Compass and connect to mongodb://localhost:27017. You'll see all your databases and collections in a user-friendly interface. It's particularly useful when you're exploring data structures or debugging complex queries.

    What's Next?#

    You've just taken your first steps into the MongoDB world! You can now install MongoDB, perform basic CRUD operations, create indexes, and even write simple aggregation pipelines. But this is just the beginning.

    In my next blog post, I’ll show you how to integrate MongoDB with Spring Boot. We'll create a proper Java application with entities, repositories, and all the Spring Data MongoDB goodness. You'll see how the Order and Product entities come to life with annotations like @Document, @Id, and @Indexed. We'll implement CRUD operations the Spring way and write tests to ensure everything works perfectly.

    So practice these commands, experiment with different query operators, and get comfortable with the MongoDB shell. Trust me, this foundation will make your Spring MongoDB journey much smoother. See you in the next post where we'll build something real with Spring Boot and MongoDB!

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more
    Spring Boot
    Mongo DB
    Spring Data MongoDB
    Mongo DB Installation

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

    More articles