MongoDB module for Testcontainers that enables running MongoDB database instances in Docker containers for integration testing
npx @tessl/cli install tessl/npm-testcontainers--mongodb@11.9.0The @testcontainers/mongodb package provides a specialized MongoDB container module for the Testcontainers framework. It enables developers to run MongoDB database instances in Docker containers for integration testing purposes, with automatic replica set configuration, authentication support, and connection string generation.
npm install @testcontainers/mongodb --save-devimport { MongoDBContainer, StartedMongoDBContainer } from "@testcontainers/mongodb";For CommonJS:
const { MongoDBContainer, StartedMongoDBContainer } = require("@testcontainers/mongodb");import { MongoDBContainer } from "@testcontainers/mongodb";
import mongoose from "mongoose";
// Start a MongoDB container
const container = await new MongoDBContainer("mongo:8").start();
// Get connection string and connect
const connectionString = container.getConnectionString();
const db = mongoose.createConnection(connectionString, { directConnection: true });
// Use the database
await db.collection("test").insertOne({ value: 1 });
const result = await db.collection("test").findOne({ value: 1 });
// Cleanup
await db.close();
await container.stop();With authentication:
const container = await new MongoDBContainer("mongo:8")
.withUsername("myuser")
.withPassword("mypassword")
.start();
const connectionString = container.getConnectionString();
// mongodb://myuser:mypassword@localhost:PORT?authSource=adminUsing async disposal (automatic cleanup):
await using container = await new MongoDBContainer("mongo:8").start();
// Container automatically stops when out of scopeThe MongoDB module extends Testcontainers' GenericContainer with MongoDB-specific functionality:
Create and configure MongoDB container instances before starting them.
class MongoDBContainer extends GenericContainer {
/**
* Creates a new MongoDB container instance
* @param image - Docker image name (e.g., "mongo:8", "mongo:7.0.14", "mongo:6")
*/
constructor(image: string);
/**
* Sets the MongoDB root username for authentication
* @param username - Username for MongoDB authentication (must not be empty)
* @returns This container instance for method chaining
* @throws Error if username is empty
*/
withUsername(username: string): this;
/**
* Sets the MongoDB root password for authentication
* @param password - Password for MongoDB authentication (must not be empty)
* @returns This container instance for method chaining
* @throws Error if password is empty
*/
withPassword(password: string): this;
/**
* Starts the MongoDB container
* @returns Promise resolving to a StartedMongoDBContainer instance
*/
start(): Promise<StartedMongoDBContainer>;
}The MongoDBContainer automatically configures:
Usage Examples:
// Basic container
const container = await new MongoDBContainer("mongo:8").start();
// With authentication
const container = await new MongoDBContainer("mongo:7")
.withUsername("admin")
.withPassword("secretpass")
.start();
// Different MongoDB versions
const mongo6 = await new MongoDBContainer("mongo:6.0.25").start();
const mongo4 = await new MongoDBContainer("mongo:4.4.29").start();Interact with running MongoDB containers to get connection information and manage the container lifecycle.
class StartedMongoDBContainer extends AbstractStartedContainer {
/**
* Returns a MongoDB connection string for connecting to the container
* @returns Connection string in the format:
* - Without auth: mongodb://host:port
* - With auth: mongodb://username:password@host:port?authSource=admin
*/
getConnectionString(): string;
/**
* Gets the host where the container is running
* @returns Host address (typically "localhost" or Docker host)
*/
getHost(): string;
/**
* Gets the mapped host port for the MongoDB port (27017)
* @param port - Internal container port (use 27017 for MongoDB)
* @param protocol - Optional protocol ("tcp" or "udp"), defaults to "tcp"
* @returns Mapped port on the host
*/
getMappedPort(port: number, protocol?: string): number;
getMappedPort(portWithProtocol: `${number}/${"tcp" | "udp"}`): number;
/**
* Gets the first mapped port from the container
* @returns First mapped port number
*/
getFirstMappedPort(): number;
/**
* Gets the container ID
* @returns Docker container ID
*/
getId(): string;
/**
* Gets the container name
* @returns Docker container name
*/
getName(): string;
/**
* Gets the container hostname
* @returns Container hostname
*/
getHostname(): string;
/**
* Gets the labels attached to the container
* @returns Object containing container labels
*/
getLabels(): Labels;
/**
* Gets the network names the container is connected to
* @returns Array of network names
*/
getNetworkNames(): string[];
/**
* Gets the network ID for a specific network name
* @param networkName - Name of the network
* @returns Network ID
*/
getNetworkId(networkName: string): string;
/**
* Gets the IP address of the container on a specific network
* @param networkName - Name of the network
* @returns IP address on that network
*/
getIpAddress(networkName: string): string;
/**
* Commits the container to a new image
* @param options - Commit options
* @returns Promise resolving to the new image ID
*/
commit(options: CommitOptions): Promise<string>;
/**
* Copies files to the running container
* @param filesToCopy - Array of file copy specifications
* @returns Promise that resolves when files are copied
*/
copyFilesToContainer(filesToCopy: FileToCopy[]): Promise<void>;
/**
* Copies directories to the running container
* @param directoriesToCopy - Array of directory copy specifications
* @returns Promise that resolves when directories are copied
*/
copyDirectoriesToContainer(directoriesToCopy: DirectoryToCopy[]): Promise<void>;
/**
* Copies content to the running container
* @param contentsToCopy - Array of content copy specifications
* @returns Promise that resolves when content is copied
*/
copyContentToContainer(contentsToCopy: ContentToCopy[]): Promise<void>;
/**
* Copies a tar archive to the running container
* @param tar - Readable stream of tar archive
* @param target - Target path in container (defaults to "/")
* @returns Promise that resolves when archive is copied
*/
copyArchiveToContainer(tar: Readable, target?: string): Promise<void>;
/**
* Copies files from the running container as a tar archive
* @param path - Path in the container to copy from
* @returns Promise resolving to readable stream of tar archive
*/
copyArchiveFromContainer(path: string): Promise<NodeJS.ReadableStream>;
/**
* Stops the container
* @param options - Optional stop configuration
* @returns Promise resolving to stopped container
*/
stop(options?: Partial<StopOptions>): Promise<StoppedTestContainer>;
/**
* Restarts the container
* @param options - Optional restart configuration
* @returns Promise that resolves when container has restarted
*/
restart(options?: Partial<RestartOptions>): Promise<void>;
/**
* Executes a command in the running container
* @param command - Command to execute (string or array of arguments)
* @param opts - Optional execution configuration
* @returns Promise resolving to execution result with exit code and output
*/
exec(command: string | string[], opts?: Partial<ExecOptions>): Promise<ExecResult>;
/**
* Retrieves container logs
* @param opts - Optional log retrieval options (since timestamp, tail count)
* @returns Promise resolving to readable stream of log output
*/
logs(opts?: { since?: number; tail?: number }): Promise<Readable>;
/**
* Async disposal support for automatic cleanup
* Enables use with 'await using' syntax
*/
[Symbol.asyncDispose](): Promise<void>;
}Usage Examples:
// Get connection details
const container = await new MongoDBContainer("mongo:8").start();
const connectionString = container.getConnectionString();
const host = container.getHost();
const port = container.getMappedPort(27017);
console.log(`MongoDB available at ${host}:${port}`);
console.log(`Connection string: ${connectionString}`);
// Execute commands in container
const result = await container.exec(["mongosh", "--eval", "db.version()"]);
console.log(result.output);
// Get logs
const logStream = await container.logs({ tail: 100 });
logStream.on("data", (chunk) => console.log(chunk.toString()));
// Restart container
await container.restart();
// Manual cleanup
await container.stop();
// Or use automatic cleanup
await using container2 = await new MongoDBContainer("mongo:8").start();
// Automatically stopped when out of scopeThe connection string from getConnectionString() works with all standard MongoDB client libraries:
// With mongoose
import mongoose from "mongoose";
const db = mongoose.createConnection(container.getConnectionString(), {
directConnection: true
});
// With native MongoDB driver
import { MongoClient } from "mongodb";
const client = await MongoClient.connect(container.getConnectionString());
// With Prisma or other ORMs
// Use container.getConnectionString() in your connection configurationinterface StopOptions {
timeout: number;
remove: boolean;
removeVolumes: boolean;
}
interface RestartOptions {
timeout: number;
}
type ExecOptions = {
workingDir: string;
user: string;
env: Record<string, string>;
};
type ExecResult = {
output: string;
stdout: string;
stderr: string;
exitCode: number;
};
interface StoppedTestContainer {
getId(): string;
copyArchiveFromContainer(path: string): Promise<NodeJS.ReadableStream>;
}
type Readable = NodeJS.ReadableStream;
type Labels = { [key: string]: string };
type CommitOptions = {
repository?: string;
tag?: string;
comment?: string;
author?: string;
pause?: boolean;
changes?: string[];
deleteOnExit?: boolean;
};
type FileToCopy = {
source: string;
target: string;
mode?: number;
};
type DirectoryToCopy = FileToCopy;
type ContentToCopy = {
content: string | Buffer | Readable;
target: string;
mode?: number;
};All MongoDB containers are automatically configured as replica sets (rs0). This is required for:
The replica set is initialized automatically during container startup as part of the health check.
The module automatically detects MongoDB version and uses:
mongosh (modern MongoDB shell)mongo (legacy MongoDB shell)Tested with MongoDB versions: 4.4, 5.x, 6.x, 7.x, 8.x
When using withUsername() and withPassword():
admin database as auth source?authSource=admin parameterMongoDB's internal port 27017 is automatically:
getMappedPort(27017) or included in getConnectionString()Always clean up containers after use:
await using syntax for automatic cleanup (recommended)stop() manually when using traditional syntax