codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

4 / 65 topics
1Introduction to MongoDB2MongoDB Architecture3Installation and Setup4Connecting to MongoDB5MongoDB Shell Basics
Tutorials/MongoDB/Connecting to MongoDB
🍃MongoDB

Connecting to MongoDB

Updated 2026-04-20
3 min read

Introduction

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. To interact with MongoDB, you need to establish a connection from your application. This tutorial will guide you through the process of connecting to MongoDB using various programming languages and tools.

Prerequisites

Before proceeding, ensure you have the following:

  • A running instance of MongoDB (either locally or on a cloud service like MongoDB Atlas).
  • Basic knowledge of the programming language you intend to use.
  • Node.js installed if you plan to use JavaScript/Node.js.

Connecting to MongoDB Using MongoDB Shell

The MongoDB Shell is an interactive JavaScript interface to MongoDB. It's useful for testing and development.

  1. Start the MongoDB Shell:

    Open your terminal or command prompt and run:

    mongo
    
  2. Connect to a Database:

    By default, it connects to the test database. To connect to another database, use:

    use mydatabase
    
  3. Perform Operations:

    You can now perform operations like inserting documents:

    db.mycollection.insertOne({ name: "John Doe", age: 30 })
    

Connecting to MongoDB Using Node.js

Node.js is a popular choice for building server-side applications, and it has excellent support for MongoDB through the mongodb package.

  1. Install the MongoDB Driver:

    First, install the driver using npm:

    npm install mongodb
    
  2. Create a Connection:

    Create a file named connect.js and add the following code:

    const { MongoClient } = require('mongodb');
    
    async function main() {
      const uri = "your_mongodb_connection_string";
      const client = new MongoClient(uri);
    
      try {
        await client.connect();
        console.log("Connected successfully to server");
    
        const database = client.db('mydatabase');
        const collection = database.collection('mycollection');
    
        // Perform operations on the collection
        const insertResult = await collection.insertOne({ name: "John Doe", age: 30 });
        console.log('Inserted document =>', insertResult);
    
      } finally {
        await client.close();
      }
    }
    
    main().catch(console.error);
    
  3. Run the Script:

    Execute the script using Node.js:

    node connect.js
    

Connecting to MongoDB Using Python

Python is another popular language for backend development, and it has a robust MongoDB driver called pymongo.

  1. Install the PyMongo Package:

    Install the package using pip:

    pip install pymongo
    
  2. Create a Connection:

    Create a file named connect.py and add the following code:

    from pymongo import MongoClient
    
    client = MongoClient("your_mongodb_connection_string")
    database = client['mydatabase']
    collection = database['mycollection']
    
    # Insert a document
    result = collection.insert_one({"name": "John Doe", "age": 30})
    print(f"Inserted document with id {result.inserted_id}")
    
  3. Run the Script:

    Execute the script using Python:

    python connect.py
    

Connecting to MongoDB Using Java

Java is widely used in enterprise environments, and it has a MongoDB driver called mongodb-driver-sync.

  1. Add the Dependency:

    If you're using Maven, add the following dependency to your pom.xml:

    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>4.3.1</version>
    </dependency>
    
  2. Create a Connection:

    Create a Java class named Connect.java and add the following code:

    import com.mongodb.client.MongoClients;
    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.MongoCollection;
    import org.bson.Document;
    
    public class Connect {
        public static void main(String[] args) {
            String uri = "your_mongodb_connection_string";
            MongoClient mongoClient = MongoClients.create(uri);
            MongoDatabase database = mongoClient.getDatabase("mydatabase");
            MongoCollection<Document> collection = database.getCollection("mycollection");
    
            // Insert a document
            Document doc = new Document("name", "John Doe").append("age", 30);
            collection.insertOne(doc);
    
            System.out.println("Inserted document successfully");
        }
    }
    
  3. Compile and Run the Code:

    Compile and run the Java class:

    javac Connect.java
    java Connect
    

Best Practices

  • Use Connection Pools: Always use connection pooling to manage database connections efficiently.
  • Handle Exceptions: Properly handle exceptions to avoid application crashes due to connectivity issues.
  • Secure Credentials: Never hard-code your MongoDB credentials in your source code. Use environment variables or configuration files instead.
  • Monitor Connections: Regularly monitor your database connections and ensure they are healthy.

Conclusion

Connecting to MongoDB is a fundamental task when building applications that require data storage. This tutorial covered connecting to MongoDB using various programming languages, including Node.js, Python, Java, and the MongoDB Shell. By following best practices and understanding the basics of connection management, you can build robust applications that interact with MongoDB effectively.

Feel free to explore more advanced features and configurations as you become more comfortable with MongoDB.


PreviousInstallation and SetupNext MongoDB Shell Basics

Recommended Gear

Installation and SetupMongoDB Shell Basics