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
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@";

// 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: "",
  info: {
    status: "active",
    whois: "",

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();


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: '',
  info: { status: 'active', whois: '' }

Golang MongoDB Connection Setup

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

go mod init

Install “” for using MongoDB driver-

go get

Install “” package for handling “BSON” data type in the code-

go get

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

// helloworld.go

package main

import (


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)

	// 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", ""},
		{"info", bson.D{
			{"status", "active"},
			{"whois", ""},

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

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

	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)

	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} {info [{status active} {whois}]}]

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-


# Import required packages
from pymongo import MongoClient

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

# Insert data to database
insertResult = testCollection.insert_one({
  "siteName": "BigBoxCode",
  "siteURL": "",
  "info": {
    "status": "active",
    "whois": "",

print("Insert Result: ", insertResult)

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

print("Find Result: ", findResult)


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': '', 'info': {'status': 'active', 'whois': ''}}

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-

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

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

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

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

$insertResult = $testCollection->insertOne([
    "siteName" => "BigBoxCode",
    "siteURL" => "",
    "info" => [
        "status" => "active",
        "whois" => "",

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-


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", "");
                put("status", "active");
                put("whois", "");
            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.");


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

Leave a Comment

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