Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

This blog on MongoDB testing will take a closer look at different features offered by MongoDB and how to perform MongoDB testing using the Selenium test automation framework.
Daniel Mascarenhas
December 22, 2025
Test automation has become an important part of product quality. Without good test automation coverage, the product cannot scale in terms of new features. In the last 20 years, I have seen how test automation teams have become the center of attention in the development team.
Software organizations are pressured to adopt new cutting-edge technologies to stay ahead. Continuous changes to the product are, hence, inevitable. Change to product functionality means change to test cases & so to the automation suite.
This change can be in any form: change in the testcase, test data, test config data, or the test report itself. Let’s say change in the test case can be handled by refactoring test cases. But what about the other changes? Can those unstructured changes be handled in a more structured way?
The answer to this question is Yes. Thanks to the new DB, which supports such data. It’s called MongoDB.
In this blog on MongoDB testing, we will take a closer look at different features offered by MongoDB and how to perform MongoDB testing using the Selenium test automation framework. If you are preparing for an interview you can learn more through Selenium interview questions.
MongoDB is an open-source database that can store large amounts of unstructured data. As opposed to rows and columns in typical SQL format, MongoDB uses non-SQL format, i.e., it stores data in collections and documents. Each collection contains a set of documents, and each document, in turn, has key-value pairs. Each document has an ID, which is the primary key and represents a unique value in a document.
As per the Stack Overflow developer survey conducted in 2023, MongoDB has been rated as the database most wanted by developers. Relational databases have been around for decades. MongoDB is a scalable, flexible NoSQL document database platform designed to overcome the relational databases approach.
It is a non-relational database. In relational databases, you need to define a schema beforehand. MongoDB doesn’t need such a requirement, making it flexible for introducing new changes. It costs less time and money.
The difference between SQL & NoSQL databases can be described below:
| SQL | NoSQL |
|---|---|
| Stands for Structured Query Language | Stands for Not Only SQL |
| Also called a Relational Database Management System (RDBMS) | Also called a Non-Relational Database Management System |
| Suitable for structured data with predefined schema | Suitable for unstructured and semi-structured data |
| Data is stored in tables with columns and rows | Data is stored in collections or documents |
| Requires vertical scaling to handle large volumes of data | Horizontal scaling makes it possible to handle large volumes of data |
| Examples: PostgreSQL, Oracle, Microsoft SQL Server | Examples: MongoDB, Cassandra, Amazon DynamoDB, Redis |
Let us now look at the key features of MongoDB.
MongoDB is an open-source database designed to support unstructured data. This DB has driver support for all popular languages like Java, Python, PHP, Node.js, C, C++, etc.
Here are some of its salient features.
Note: Run automated test suites on 3000+ environments. Try TestMu AI Today!
Integrating MongoDB with Selenium, the powerful web automation framework, offers a compelling synergy that revolutionizes how we handle test data in the world of test automation.
While Selenium is renowned for automating web applications with precision and efficiency, MongoDB, a NoSQL database, is celebrated for its flexibility and scalability in data storage.
Combining these two technologies empowers testers and developers alike to manage test data dynamically, streamline test case execution, and enhance the overall efficiency of the testing process.
This section of the MongoDB testing tutorial will explore why incorporating MongoDB into your Selenium automation stack can lead to more robust and adaptable testing solutions.
MongoDB’s NoSQL architecture pairs seamlessly with Selenium’s web automation capabilities, offering a dynamic approach to managing test data. In this section of the MongoDB testing tutorial, I will walk you through the steps to set up MongoDB with Selenium, including installing MongoDB and MongoDB Compass and creating a sample MongoDB database using Compass.
When writing this blog on MongoDB testing, MongoDB version 6.0.6 is available. However, the Klov server we will use in this blog is incompatible with that MongoDB version. Hence, we will install MongoDB version 5.0.17 on Windows for this exercise.
Note: –bind_ip_all flag is required if MongoDB installed is on Windows to avoid connectivity issues. The default port is 27017. So even if it is not passed explicitly, that’s fine.
Command output would look something like this.:

MongoDB Compass is the UI client for MongoDB, where we visualize our data. We can interact with data using full CRUD functionality. We can run ad-hoc queries. We can also view and optimize the query performance. It is available on Linux, Mac, or Windows. Compass empowers us to make smarter decisions about indexing, document validation, and more. For this exercise, we will use Windows Server 2016; the steps might differ if you are using any other OS.




Our MongoDB is set up!
CEO, Vercel
Discovered @TestMu AI yesterday. Best browser testing tool I've found for my use case. Great pricing model for the limited testing I do 👏
Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud
Let’s dive in and learn how to create Selenium scripts that establish a robust connection to MongoDB, unlocking possibilities for your MongoDB testing endeavors.

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>4.8.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-support</artifactId>
<version>4.8.3</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.4.0</version>
</dependency>
For Selenium and TestNG libraries, we have added below the entries into pom.xml.
For MongoDB Java drivers, the below library is added.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.13</version>
</dependency>
Besides the above libraries in pom.xml, we have added Maven plugins to build the project.
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${javac.version}</source>
<target>${javac.version}</target>
</configuration>
</plugin>
</plugins>
Finally, Java version 11 has been set to be used for compiling.
<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
Import statements: We need to import several libraries to accomplish our exercise.
connectToMongoDB(): Function to initialize and connect to MongoDB.
@BeforeClass
public void connectToMongoDB(){
// Connect to MongoDB by giving {MongoDBHost}
mongoClient = new MongoClient("{MongoDBHost}", 27017);
// Get Database handle by replacing {MongoDBName} with DB name
database = mongoClient.getDatabase("{MongoDBName}");
// Get collection handle by giving collection name created in MongoDB.
test_execution_info = database.getCollection("test_execution_details");
}
This function will initialize MongoClient and establish a DB connection with the MongoDB database and collection.
Provide the connection parameters to it.
{MongoDBHost}: IP Address of the machine where MongoDB is hosted.
Sometimes, we face issues binding to localhost on Windows. To avoid this, on the MongoDB host, open cmd and run ipconfig. Use the ‘ipv4 address’ as IP for connecting to MongoDB via script.
{MongoDBName}: Database ‘Demo’ created in earlier steps.
{MongoDBPort}: 27017
browserSetup(): Function to initialize browser setup.
private void browserSetup(){
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.setBrowserVersion("109");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.MILLISECONDS);
}
We use WebDriver Manager to instantiate Chrome WebDriver instances. We will launch the browser in a headless manner.
Test1() and Test2(): Test methods
Let’s look at the two test methods, Test1 and Test2. These will perform simple checks on the LambadaTest application. It would also append test cases and test execution info into MongoDB.
@Test
public void Test1(){
browserSetup();
// Create one MongoDB document to store test results of this test, Test1
doc = new Document("testname", "MongoDBTest 1");
// Lets append, some fields and value pairs into MongoDB document as below
doc.append("testname", "MongoDBTest 1");
doc.append("description", "Detailed description of a positive test, test 1");
doc.append("author","Guru");
//Login to Lambdatest demo url
driver.get(baseURL);
driver.findElement(By.xpath(enterMessage)).sendKeys("MongoDBTest MongoDB");
driver.findElement(By.xpath((getCheckedValue))).click();
// Lets set the test result accordingly into MongoDB document
if (driver.findElement(By.xpath(yourMessage)).isDisplayed()){
doc.append("status","PASS");
} else{
doc.append("status","FAIL");
}
// Finally, Lets now insert document into collection
test_execution_info.insertOne(doc);
}
In Test1(), we first create a document by passing the document and test names. We can then append details in key-value pairs. Once a pair of values is appended, we insert that document into the MongoDB collection at the end.
@Test
public void Test2(){
browserSetup();
// Create one MongoDB document to store test results of this test, Test2
doc = new Document("testname", "MongoDBTest 2");
// Lets append, some fields and value pairs into MongoDB document as below
doc.append("testname", "MongoDBTest 2");
doc.append("description", "Detailed description of a negative test, MongoDBTest 2");
doc.append("author","Geeta");
// Login to Lambdatest demo url
driver.get(baseURL);
driver.findElement(By.xpath(enterMessage)).sendKeys("MongoDBTest MongoDB");
driver.findElement(By.xpath((getCheckedValue))).click();
// Lets set the test result accordingly into MongoDB document
if (!driver.findElement(By.xpath(yourMessage)).isDisplayed()){
doc.append("status","FAIL");
} else{
doc.append("status","PASS");
}
// Finally, Lets now insert document into collection
test_execution_info.insertOne(doc);
}
otherCRUDOperations(): This method showcases how different CRUD operations can be performed on MongoDB.
@Test
public void otherCRUDOperations(){
// Create one simple test & append its result into MongoDB
doc = new Document("testname", "MongoDB update test");
doc.append("testname", "MongoDB test");
doc.append("description", "Some description");
doc.append("author","Gopal");
//Some test steps here
//Some test steps here
//Some test steps here
doc.append("status","PASS");
test_execution_info.insertOne(doc);
//Now Lets update the record of same document
//Retrieve the id of that particular document
ObjectId docId = doc.getObjectId("_id");
//Construct a MongoDB query where id is equals to particular id. Using Filters we can construct desired query
Bson query = Filters.eq("_id", docId);
//Create a set of values to be updated,
BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("testname", "MongoDB test Updated"));
//This method will first execute the query. It would then update first record (of search results) with below set of values
test_execution_info.updateOne(query,set);
//We can also delete the document
test_execution_info.deleteOne(query);
}
After updating connection details, execute the script via IDE.

Once the test is executed, go back to MongoDB to check the test execution data.
As we can see below, data has been populated into MongoDB.

Let’s rerun the same test class to see how new execution data is getting appended into MongoDB.
We can see below MongoDB has inserted data for the next run. Since MongoDB assigned an object id for every record, it becomes easier to track historical data. We can use this historic execution data to build new reports or apply analytics.

So, this is how we can interact with MongoDB via Selenium scripts. MongoDB can help testers build test scripts that are resilient to any change. We can even build reports from scratch by leveraging MongoDB documents and collections.
Let’s now take an example of one third-party test automation reporting tool leveraging MongoDB to build sophisticated test automation reports.
Note: Automate your test scripts with Selenium on the cloud. Try TestMu AI Today!
As some might be familiar, Extent Report is one open-source reporting library useful for test automation. It can be easily integrated with major test automation frameworks like JUnit, TestNG, JGiven, etc. These reports have pie chart representation, test stepwise report generation, screenshots for failing test cases, etc. Due to a good, presentable user interface, these reports can be shared with all stakeholders.
Extent reports have gone one step ahead and leveraged MongoDB to build a real-time analytic report server called ‘Klov’.
Klov is a reporting server for extent reports. It provides a detailed analysis of our most recent builds. It enables us to leverage historical data to analyze how tests have performed against AUT (Application under test). It works with the Extent Report Library to push data into a MongoDB instance. And then, these reports are published on the Klov server.
To use the Klov server, we should use extent reports in our tests. Let’s see how we can rewrite the earlier test using Klov for MongoDB.
Installation of Klov is very simple. As the community version is Docker-based, we must deploy the container image to Docker.









<dependency>
<groupId>com.aventstack</groupId>
<artifactId>klov-reporter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.8</version>
</dependency>
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentKlovReporter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import java.util.concurrent.TimeUnit;
@BeforeClass
private void klovSetup(){
ExtentKlovReporter klov = new ExtentKlovReporter("LambdaTest");
klov.initMongoDbConnection("{MongoDBHost}",27017);
klov.initKlovServerConnection("http://{KlovHost}:{KlovPort}");
//Create an instance of ExtentReports.
extent = new ExtentReports();
// Attach Extent Reports to Klov Server. This will publish the Extent reports of all the tests of this class to Klov server
extent.attachReporter(klov);
}
private void browserSetup(){
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.MILLISECONDS);
}
@Test
public void Test1(){
browserSetup();
// Create entry for this test into extent report. By giving key details, such as Test name, description, author etc.
extentTest = extent.createTest("MongoDBTest 1", "Detailed description of test 1");
extentTest.assignAuthor("Guru");
// Log information about your test into the extent report
extentTest.info("Started with MongoDBTest 1");
driver.get(baseURL);
driver.findElement(By.xpath(enterMessage)).sendKeys("MongoDBTest MongoDB");
driver.findElement(By.xpath((getCheckedValue))).click();
// Based on testcase checkpoints, append final execution status into extent Report
try {
Assert.assertEquals(driver.findElement(By.xpath(yourMessage)).isDisplayed(), true, "Message is not matched.");
extentTest.pass("PASS");
}catch(AssertionError e){
extentTest.fail("FAIL: "+e.getMessage());
}
}
@Test
public void Test2(){
browserSetup();
// Create entry for this test into extent report. By giving key details, such as Test name, description, author etc
extentTest = extent.createTest("MongoDBTest 2", "Detailed description of test 2");
extentTest.assignAuthor("Geeta");
// Log information about your test into the extent report
extentTest.info("Started with MongoDBTest 2");
driver.get(baseURL);
driver.findElement(By.xpath(enterMessage)).sendKeys("MongoDBTest MongoDB");
driver.findElement(By.xpath((getCheckedValue))).click();
// Based on testcase checkpoints, append final execution status into extent Report
try {
Assert.assertEquals(driver.findElement(By.xpath(yourMessage)).isDisplayed(), false, "Message is matched.");
extentTest.pass("PASS");
}catch(AssertionError e){
extentTest.fail("FAIL: "+e.getMessage());
}
}
Did you find this page helpful?
More Related Hubs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance