MongoDB: Client Library/Driver Connection Setup

Here is how to set up a connection from your preferred programming language. We have discussed the setup for NodeJS, Golang, Java, Python here.

Here are the packages we have used-

Programming LanguageDocumentationPackage Source
NodeJS MongoDB Node.JS Driver Documentation
MongoDB Node.JS Driver NPM
GitHub
Goalng Golang Mongo Driver Documentation GitHub
Python PyMongo Documentation GitHub
Java Java Mongo Driver Documentation GitHub
C# C# Mongo Driver Documentation GitHub
PHP PHP Mongo Driver Documentation
Pecl Mongo Package Installation
PHP Package in Packagist
Driver code in GitHub
Library code in GitHub

NodeJS MongoDB Connection Setup

Initialize a NodeJS project, and provide the required information asked in the terminal-

npm init

This will initialize a Node project and create “package.json” file.

To connect to MongoDB we need a package named “mongodb“. Let’s install the package, by using the following command-

npm install --save mongodb

Here is our package.json file, your file will look similar-

{
  "name": "mongoexample",
  "version": "1.0.0",
  "description": "Mongodb usage examples",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "webhkp",
  "license": "ISC",
  "dependencies": {
    "mongodb": "^6.3.0"
  }
}

To test the installation, let’s create a JavaScript file named “hello-world.js“, and the following code to the file-

// hello-world.js

import { MongoClient } from "mongodb";

// Define MongoDB connection URI
const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";

// Create a client
const mongo = new MongoClient(uri);

await mongo.connect();

const database = mongo.db("bigboxcode");
const testCollection = database.collection("mytest");

// Insert data
const insertResult = await testCollection.insertOne({
  siteName: "BigBoxCode",
  siteURL: "https://bigboxcode.com",
  info: {
    status: "active",
    whois: "whois.bigboxcode.com",
  },
});

console.log("Insert Result: ", insertResult);

// Read data
const findResult = await testCollection.findOne({
  _id: insertResult.insertedId,
});

console.log("Find Result: ", findResult);

// Close connection
await mongo.close();

process.exit(0);

Run the code using the following command-

node hello-word.js

We will get the following output-

Insert Result:  
{
  acknowledged: true,
  insertedId: new ObjectId('65a0028b52ca36d21b4279c7')
}

Find Result:  
{
  _id: new ObjectId('65a0028b52ca36d21b4279c7'),
  siteName: 'BigBoxCode',
  siteURL: 'https://bigboxcode.com',
  info: { status: 'active', whois: 'whois.bigboxcode.com' }
}

Golang MongoDB Connection Setup

Initialize a go module for your project, using the command below. Our package name is “github.com/webhkp/bigboxcode” here, but your package name will be different, so use your package name-

go mod init github.com/webhkp/bigboxcode

Install “go.mongodb.org/mongo-driver/mongo” for using MongoDB driver-

go get go.mongodb.org/mongo-driver/mongo

Install “go.mongodb.org/mongo-driver/bson” package for handling “BSON” data type in the code-

go get go.mongodb.org/mongo-driver/bson

Create a go file named “helloworld.go“, and add the following code-

// helloworld.go

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"

func main() {
	// Initiate mongo client
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		fmt.Println("MongoDB connection error: ", err)
		os.Exit(1)
	}

	// Initiate collection instance
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	testCollection := mongoClient.Database("bigboxcode").Collection("mytest")

	// Insert data
	insertData := bson.D{
		{"siteName", "BigBoxCode"},
		{"siteURL", "https://bigboxcode.com"},
		{"info", bson.D{
			{"status", "active"},
			{"whois", "whois.bigboxcode.com"},
		}},
	}

	insertResult, err := testCollection.InsertOne(ctx, insertData)

	if err != nil {
		fmt.Println("Data insert error: ", err)
		os.Exit(1)
	}

	fmt.Println("Insert Result: ", insertResult)

	// Retrieve last inserted data
	var findResult bson.D

	if err := testCollection.FindOne(ctx, bson.D{{"_id", insertResult.InsertedID}}).Decode(&findResult); err != nil {
		fmt.Println("Data insert error: ", err)
		os.Exit(1)
	}

	fmt.Println("Inserted data: ", findResult)
}

Run it using the following command-

go run helloworld.go

You should get output like below-

Insert Result:  &{ObjectID("65a12726cab651d53b29fe23")}
Inserted data:  [{_id ObjectID("65a12726cab651d53b29fe23")} {siteName BigBoxCode} {siteURL https://bigboxcode.com} {info [{status active} {whois whois.bigboxcode.com}]}]

Python Connection Setup for MongoDB

We are using the package “pymongo” for connecting to MongoDB. Use the following command to install the Python “pymongo” package-

pip install pymongo

Create a Python file and the following code-

# helloworld.py

# Import required packages
from pymongo import MongoClient

# Create MongoDB client
mongoClient = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")
# Select database and collection
mongoDatabase = mongoClient.bigboxcode
testCollection = mongoDatabase.mytest

# Insert data to database
insertResult = testCollection.insert_one({
  "siteName": "BigBoxCode",
  "siteURL": "https://bigboxcode.com",
  "info": {
    "status": "active",
    "whois": "whois.bigboxcode.com",
  },
})

print("Insert Result: ", insertResult)

# Read the inserted data
findResult = testCollection.find_one({"_id": insertResult.inserted_id})

print("Find Result: ", findResult)

Output:

If we run the above code, we will get following code-

Insert Result:  InsertOneResult(ObjectId('65a267a73eafc3e3e4165242'), acknowledged=True)
Find Result:  {'_id': ObjectId('65a267a73eafc3e3e4165242'), 'siteName': 'BigBoxCode', 'siteURL': 'https://bigboxcode.com', 'info': {'status': 'active', 'whois': 'whois.bigboxcode.com'}}

PHP Connection Setup for MongoDB

We are using the Ppackage “mongodb/mongodb” for connecting to MongoDB.

Use the following composer command to initiate a new project. Project information asked in the terminal-

composer init

This will generate a “composer.json” file. We have the following in “composer.json”, you may have some different information based on the information you provided-

{
    "name": "webhkp/mongophp",
    "type": "project",
    "autoload": {
        "psr-4": {
            "Webhkp\\Mongophp\\": ""
        }
    },
    "authors": [
        {
            "name": "webhkp"
        }
    ],
    "require": {}
}

Before installing the composer package we need to install the “mongdb” library-

pecl install mongodb

Add the composer package by using the following command-

composer require mongodb/mongodb

Use the code below to connect to MongoDB and perform operations-

<?php
require_once __DIR__ . '/vendor/autoload.php';

$uri = 'mongodb://bigboxuser:bigboxpass@127.0.0.1:27017';

$client = new MongoDB\Client($uri);

$testCollection = $client->selectDatabase('bigboxcode')->selectCollection('mytest');

$insertResult = $testCollection->insertOne([
    "siteName" => "BigBoxCode",
    "siteURL" => "https://bigboxcode.com",
    "info" => [
        "status" => "active",
        "whois" => "whois.bigboxcode.com",
    ],
]);

Java MongoDB Connection Setup

We are using the package “mongodb-driver-sync” for connecting to MongoDB. Use the following to add the package from Maven-

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver-sync</artifactId>
        <version>4.11.1</version>
    </dependency>
</dependencies>

If you are using Gradle, then use the following setting-

dependencies {
  implementation 'org.mongodb:mongodb-driver-sync:4.11.1'
}

Use the code below, to check the MongoDB connection-

import com.mongodb.client.result.InsertOneResult;
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import java.util.HashMap;
import java.util.Map;

import static com.mongodb.client.model.Filters.eq;

public class Main {
    public static void main(String[] args) {

        // Replace the placeholder with your MongoDB deployment's connection string
        String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("bigboxcode");
            MongoCollection<Document> testCollection = database.getCollection("mytest");

            // Insert a document
            Map<String, String> documentData = new HashMap<>() {{
                put("siteName", "BigBoxCode");
                put("siteURL", "https://bigboxcode.com");
                put("status", "active");
                put("whois", "whois.bigboxcode.com");
            }};
            Document insertDocument = new Document(documentData);
            InsertOneResult insertResult = testCollection.insertOne(insertDocument);

            System.out.println("Insert Result: " + insertResult);

            // Find the result
            Document findResult = testCollection.find(eq("_id", insertResult.getInsertedId())).first();
            if (findResult != null) {
                System.out.println("Find Result: " + findResult.toJson());
            } else {
                System.out.println("Not found.");
            }
        }
    }
}

Output:


Insert Result: AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=65a2582e87695558dfee4c5f}}
Find Result: {"_id": {"$oid": "65a2582e87695558dfee4c5f"}, "siteURL": "https://bigboxcode.com", "whois": "whois.bigboxcode.com", "siteName": "BigBoxCode", "status": "active"}

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.