Skip to main content

Actions

The ballerinax/mongodb package exposes the following clients:

ClientPurpose
ClientTop-level client for connecting to MongoDB, listing databases, and obtaining Database references.
DatabaseRepresents a MongoDB database. Manage collections and drop the database.
CollectionDocument CRUD, queries, aggregation pipelines, distinct values, and index management.
Error types

All operations return errors as mongodb:Error, a union of mongodb:DatabaseError, mongodb:ApplicationError, and Ballerina's built-in error. mongodb:DatabaseError carries an additional mongoDBExceptionType detail field for command-level failures.


Client

Top-level client for connecting to MongoDB, listing databases, and obtaining Database references.

Configuration

FieldTypeDefaultDescription
connectionConnectionParameters|stringRequiredStructured connection parameters or a MongoDB connection string URI.
optionsConnectionProperties?()Optional connection properties (read concern, write concern, pool settings, SSL, timeouts).

Initializing the client

import ballerinax/mongodb;

configurable string connectionUri = ?;

mongodb:Client mongoClient = check new ({
connection: connectionUri
});

Operations

Database management

listDatabaseNames

Lists all database names in the MongoDB server.

Returns: string[]|mongodb:Error

Sample code:

string[] databases = check mongoClient->listDatabaseNames();

Sample response:

["admin", "local", "movies", "orders"]
getDatabase

Retrieves a Database object for the named database.

Parameters:

NameTypeRequiredDescription
databaseNamestringYesName of the database to retrieve.

Returns: mongodb:Database|mongodb:Error

Sample code:

mongodb:Database moviesDb = check mongoClient->getDatabase("movies");
close

Closes the MongoDB client connection. Use a single client instance for the application lifetime.

Returns: mongodb:Error?

Sample code:

check mongoClient->close();

Database

Represents a MongoDB database. Manage collections and drop the database.

Configuration

Database has no direct configuration. Instances are obtained through Client->getDatabase().

Initializing the client

import ballerinax/mongodb;

// Obtain a Database via Client->getDatabase()
mongodb:Client mongoClient = check new ({
connection: "mongodb://localhost:27017"
});
mongodb:Database moviesDb = check mongoClient->getDatabase("movies");

Operations

Collection management

listCollectionNames

Lists all collection names in the database.

Returns: string[]|mongodb:Error

Sample code:

string[] collections = check moviesDb->listCollectionNames();

Sample response:

["movies", "directors", "reviews"]
createCollection

Creates a new collection in the database.

Parameters:

NameTypeRequiredDescription
collectionNamestringYesName of the collection to create.

Returns: mongodb:Error?

Sample code:

check moviesDb->createCollection("movies");
getCollection

Gets a Collection object for the named collection.

Parameters:

NameTypeRequiredDescription
collectionNamestringYesName of the collection to retrieve.

Returns: mongodb:Collection|mongodb:Error

Sample code:

mongodb:Collection moviesCollection = check moviesDb->getCollection("movies");

Database operations

drop

Drops the entire database and all its collections.

Returns: mongodb:Error?

Sample code:

check moviesDb->drop();

Collection

Document CRUD, queries, aggregation pipelines, distinct values, and index management.

Configuration

Collection has no direct configuration. Instances are obtained through Database->getCollection().

Initializing the client

import ballerinax/mongodb;

// Obtain a Collection via Database->getCollection()
mongodb:Client mongoClient = check new ({
connection: "mongodb://localhost:27017"
});
mongodb:Database db = check mongoClient->getDatabase("movies");
mongodb:Collection moviesCollection = check db->getCollection("movies");

Operations

Insert operations

insertOne

Inserts a single document into the collection.

Parameters:

NameTypeRequiredDescription
documentrecord {|anydata...;|}YesThe document to insert.
optionsInsertOneOptionsNoInsert options (comment, bypassDocumentValidation).

Returns: mongodb:Error?

Sample code:

check moviesCollection->insertOne({
title: "Inception",
year: 2010,
director: "Christopher Nolan"
});
insertMany

Inserts multiple documents into the collection. When ordered is true (default), insertion stops on the first error.

Parameters:

NameTypeRequiredDescription
documentsrecord {|anydata...;|}[]YesArray of documents to insert.
optionsInsertManyOptionsNoInsert options (comment, bypassDocumentValidation, ordered).

Returns: mongodb:Error?

Sample code:

check moviesCollection->insertMany([
{title: "The Dark Knight", year: 2008, director: "Christopher Nolan"},
{title: "Interstellar", year: 2014, director: "Christopher Nolan"},
{title: "Parasite", year: 2019, director: "Bong Joon-ho"}
]);

Query operations

find

Finds all documents matching the filter and returns a stream of typed records.

Parameters:

NameTypeRequiredDescription
filtermap<json>NoQuery filter document. Defaults to {} (match all).
findOptionsFindOptionsNoSort, limit, skip, and batchSize options.
projectionmap<json>?NoProjection document to include or exclude fields.
targetTypetypedesc<record {|anydata...;|}>NoExpected record type for results (inferred from context).

Returns: stream<targetType, error?>|mongodb:Error

Sample code:

type Movie record {|
string title;
int year;
string director;
|};

stream<Movie, error?> result = check moviesCollection->find({year: 2010});
Movie[] movies = check from Movie m in result select m;

Sample response:

[{"title": "Inception", "year": 2010, "director": "Christopher Nolan"}]
findOne

Finds the first document matching the filter. Returns () if no match is found.

Parameters:

NameTypeRequiredDescription
filtermap<json>NoQuery filter document.
findOptionsFindOptionsNoSort, limit, skip, and batchSize options.
projectionmap<json>?NoProjection document to include or exclude fields.
targetTypetypedesc<record {|anydata...;|}>NoExpected record type (inferred from context).

Returns: targetType|mongodb:Error?

Sample code:

Movie? movie = check moviesCollection->findOne({title: "Inception"});

Sample response:

{"title": "Inception", "year": 2010, "director": "Christopher Nolan"}
countDocuments

Counts documents in the collection matching the filter.

Parameters:

NameTypeRequiredDescription
filtermap<json>NoQuery filter document. Defaults to {} (count all).
optionsCountOptionsNoOptions for limit, skip, maxTimeMS, and hint.

Returns: int|mongodb:Error

Sample code:

int count = check moviesCollection->countDocuments({director: "Christopher Nolan"});

Sample response:

3
distinct

Returns distinct values for a given field across matching documents.

Parameters:

NameTypeRequiredDescription
fieldNamestringYesThe field name to get distinct values for.
filtermap<json>NoQuery filter document. Defaults to {} (all documents).
targetTypetypedesc<anydata>NoType for distinct values (inferred from context).

Returns: stream<targetType, error?>|mongodb:Error

Sample code:

stream<string, error?> directors = check moviesCollection->'distinct("director", {});
string[] uniqueDirectors = check from string d in directors select d;

Sample response:

["Christopher Nolan", "Bong Joon-ho"]

Update operations

updateOne

Updates the first document matching the filter using MongoDB update operators.

Parameters:

NameTypeRequiredDescription
filtermap<json>YesFilter to match the document to update.
updateUpdateYesUpdate operators record (set, unset, inc, mul, rename, etc.).
optionsUpdateOptionsNoOptions for upsert, bypassDocumentValidation, comment, hint, and hintString.

Returns: UpdateResult|mongodb:Error

Sample code:

mongodb:UpdateResult result = check moviesCollection->updateOne(
{title: "Inception"},
{set: {year: 2010, rating: 8.8}}
);

Sample response:

{"matchedCount": 1, "modifiedCount": 1}
note

The upsertedId field appears in the response only when the operation performs an upsert (upsert: true is set in UpdateOptions and a new document is inserted as a result). For non-upsert calls like the sample above, the field is omitted from the result entirely.

updateMany

Updates all documents matching the filter using MongoDB update operators.

Parameters:

NameTypeRequiredDescription
filtermap<json>YesFilter to match documents to update.
updateUpdateYesUpdate operators record.
optionsUpdateOptionsNoOptions for upsert, bypassDocumentValidation, comment, hint, and hintString.

Returns: UpdateResult|mongodb:Error

Sample code:

mongodb:UpdateResult result = check moviesCollection->updateMany(
{director: "Christopher Nolan"},
{set: {genre: "Sci-Fi"}}
);

Sample response:

{"matchedCount": 3, "modifiedCount": 3}
note

The upsertedId field appears in the response only when the operation performs an upsert. For non-upsert calls like the sample above, the field is omitted from the result entirely.

Delete operations

deleteOne

Deletes the first document matching the filter.

Parameters:

NameTypeRequiredDescription
filtermap<json>YesFilter to match the document to delete.

Returns: DeleteResult|mongodb:Error

Sample code:

mongodb:DeleteResult result = check moviesCollection->deleteOne({title: "Inception"});

Sample response:

{"deletedCount": 1, "acknowledged": true}
deleteMany

Deletes all documents matching the filter.

Parameters:

NameTypeRequiredDescription
filterstring|map<json>YesFilter for documents to delete.

Returns: DeleteResult|mongodb:Error

Sample code:

mongodb:DeleteResult result = check moviesCollection->deleteMany({director: "Christopher Nolan"});

Sample response:

{"deletedCount": 3, "acknowledged": true}

Aggregation

aggregate

Runs an aggregation pipeline on the collection. Supports stages like $match, $group, $lookup, $sort, $project, $limit, and more.

Parameters:

NameTypeRequiredDescription
pipelinemap<json>[]YesArray of aggregation pipeline stage documents.
targetTypetypedesc<anydata>NoExpected result type (inferred from context).

Returns: stream<targetType, error?>|mongodb:Error

Sample code:

type DirectorSummary record {|
string _id;
int movieCount;
|};

stream<DirectorSummary, error?> result = check moviesCollection->aggregate([
{"$group": {"_id": "$director", "movieCount": {"$sum": 1}}},
{"$sort": {"movieCount": -1}}
]);
DirectorSummary[] summaries = check from DirectorSummary s in result select s;

Sample response:

[{"_id": "Christopher Nolan", "movieCount": 3}, {"_id": "Bong Joon-ho", "movieCount": 1}]

Index management

createIndex

Creates an index on the collection with the given key specification and options.

Parameters:

NameTypeRequiredDescription
keysmap<json>YesIndex key specification (field name to direction, for example {"title": 1} for ascending).
optionsCreateIndexOptionsNoIndex options (unique, sparse, name, expireAfterSeconds, etc.).

Returns: mongodb:Error?

Sample code:

check moviesCollection->createIndex({"title": 1}, {unique: true, name: "title_unique_idx"});
listIndexes

Lists all indexes on the collection.

Returns: stream<Index, error?>|mongodb:Error

Sample code:

stream<mongodb:Index, error?> indexes = check moviesCollection->listIndexes();
mongodb:Index[] indexList = check from mongodb:Index idx in indexes select idx;

Sample response:

[{"ns": "movies.movies", "v": 2, "name": "_id_", "key": {"_id": 1}}, {"ns": "movies.movies", "v": 2, "name": "title_unique_idx", "key": {"title": 1}}]
dropIndex

Drops the named index from the collection.

Parameters:

NameTypeRequiredDescription
indexNamestringYesName of the index to drop.

Returns: mongodb:Error?

Sample code:

check moviesCollection->dropIndex("title_unique_idx");
dropIndexes

Drops all indexes on the collection except the default _id index.

Returns: mongodb:Error?

Sample code:

check moviesCollection->dropIndexes();

Collection operations

name

Returns the name of the collection. This is not a remote method, it does not invoke a network call.

Returns: string

Sample code:

string collectionName = moviesCollection.name();
drop

Drops the entire collection from the database.

Returns: mongodb:Error?

Sample code:

check moviesCollection->drop();

Supporting types

ConnectionParameters

Structured connection parameters used in ConnectionConfig.connection.

FieldTypeDefaultDescription
serverAddressServerAddress|ServerAddress[]{}A single server address, or an array for replica sets and sharded clusters.
authBasicAuthCredential|ScramSha1AuthCredential|ScramSha256AuthCredential|X509Credential|GssApiCredential()Optional. Authentication credentials: pick the record that matches your server's configured auth mechanism. See Authentication credentials below.

ServerAddress

FieldTypeDefaultDescription
hoststring"localhost"MongoDB server hostname or IP.
portint27017MongoDB server port.

Authentication credentials

The auth field of ConnectionParameters accepts one of five records, each tagged with a fixed authMechanism constant. Pick the record that matches the auth mechanism configured on your MongoDB server.

BasicAuthCredential: PLAIN

FieldTypeDefaultDescription
authMechanismAUTH_PLAINAUTH_PLAINAlways "PLAIN". Read-only.
usernamestringRequiredUsername.
passwordstringRequiredPassword.
databasestringRequiredAuthentication source database (typically "admin").

ScramSha1AuthCredential: SCRAM-SHA-1

Same field shape as BasicAuthCredential. The authMechanism is the constant AUTH_SCRAM_SHA_1 ("SCRAM_SHA_1").

ScramSha256AuthCredential: SCRAM-SHA-256

Same field shape as BasicAuthCredential. The authMechanism is the constant AUTH_SCRAM_SHA_256 ("SCRAM_SHA_256"). This is the default mechanism on modern MongoDB servers.

X509Credential: MongoDB X.509

FieldTypeDefaultDescription
authMechanismAUTH_MONGODB_X509AUTH_MONGODB_X509Always "MONGODB_X509". Read-only.
usernamestring?()Optional username for client-certificate authentication. Omit to use the certificate subject.

GssApiCredential: GSSAPI / Kerberos

FieldTypeDefaultDescription
authMechanismAUTH_GSSAPIAUTH_GSSAPIAlways "GSSAPI". Read-only.
usernamestringRequiredKerberos principal username.
serviceNamestring?()Override the default service name ("mongodb").

ConnectionProperties

Optional connection-level settings passed via ConnectionConfig.options.

FieldTypeDefaultDescription
readConcernReadConcern?()Read concern level (see below).
writeConcernstring?()Write concern level (for example "majority").
readPreferencestring?()Read preference for replica sets (for example "secondaryPreferred").
replicaSetstring?()Replica-set name. The driver uses it to validate that the cluster matches.
sslEnabledbooleanfalseEnable SSL/TLS. Set secureSocket together with this when a custom trust chain is needed.
invalidHostNameAllowedbooleanfalseAllow invalid hostnames in TLS handshakes.
secureSocketSecureSocket?()TLS keystore and truststore configuration. Required when sslEnabled is true and you provide custom certificates.
retryWritesboolean?()Retry writes on transient errors.
socketTimeoutint?()Socket timeout in milliseconds.
connectionTimeoutint?()Connection timeout in milliseconds.
maxPoolSizeint?()Maximum connections in the pool.
maxIdleTimeint?()Maximum idle time of a pooled connection (milliseconds).
maxLifeTimeint?()Maximum lifetime of a pooled connection (milliseconds).
minPoolSizeint?()Minimum pool size.
localThresholdint?()Local-threshold latency for server selection (milliseconds).
heartbeatFrequencyint?()Frequency of cluster heartbeats (milliseconds).

SecureSocket

FieldTypeDefaultDescription
trustStorecrypto:TrustStoreRequiredTruststore (JKS or PKCS12) holding the CA certificates the client trusts.
keyStorecrypto:KeyStoreRequiredKeystore holding the client certificate (used for X.509 auth or mutual TLS).
protocolstringRequiredTLS protocol name (for example "TLS", "TLSv1.2", "TLSv1.3").

ReadConcern

A union of the supported read-concern levels:

ConstantValueDescription
LOCAL"local"Default. Returns data from the queried node without durability guarantees.
AVAILABLE"available"Like LOCAL but more permissive on sharded clusters.
MAJORITY"majority"Returns data acknowledged by a majority of replica-set members.
LINEARIZABLE"linearizable"Returns data reflecting all majority-acknowledged writes that completed before the read.
SNAPSHOT"snapshot"For use within multi-document transactions.

InsertOneOptions

FieldTypeDefaultDescription
commentstring?()Comment included with the operation in MongoDB logs.
bypassDocumentValidationbooleanfalseSkip server-side schema validation.

InsertManyOptions

FieldTypeDefaultDescription
commentstring?()Comment included with the operation.
bypassDocumentValidationbooleanfalseSkip server-side schema validation.
orderedbooleantrueWhen true, insertion stops at the first error. When false, the connector attempts every document and reports per-document failures.

FindOptions

FieldTypeDefaultDescription
sortmap<json>{}Sort specification (for example {"year": -1}).
limitint?()Maximum number of documents to return.
batchSizeint?()Cursor batch size.
skipint?()Number of documents to skip.

CountOptions

FieldTypeDefaultDescription
limitint?()Maximum number of documents to count.
skipint?()Number of documents to skip before counting.
maxTimeMSint?()Maximum time the operation can run, in milliseconds.
hintstring?()Hint as a JSON string indicating which index to use.

CreateIndexOptions

FieldTypeDefaultDescription
backgroundboolean?()Build the index in the background (legacy MongoDB).
uniqueboolean?()Enforce uniqueness on the indexed fields.
namestring?()Custom index name.
sparseboolean?()Index only documents where the indexed field exists.
expireAfterSecondsint?()TTL on documents in the collection. Creates a TTL index.
versionint?()Index version number.
weightsmap<json>?()Per-field weights for text indexes.
defaultLanguagestring?()Default language for text indexes.
languageOverridestring?()Field name that overrides the default language per document.
textVersionint?()Text-index version.
sphereVersionint?()2dsphere-index version.
bitsint?()2d-index geohash precision.
minfloat?()2d-index minimum boundary.
maxfloat?()2d-index maximum boundary.
partialFilterExpressionmap<json>{}Filter expression for partial indexes.
hiddenboolean?()Hide the index from the query planner.

UpdateOptions

FieldTypeDefaultDescription
upsertbooleanfalseInsert a new document if no match is found.
bypassDocumentValidationbooleanfalseSkip server-side schema validation.
commentstring?()Comment included with the operation.
hintmap<json>?()Hint as a document indicating which index to use.
hintStringstring?()Hint as a string indicating which index to use.

Update

A record where each field corresponds to a MongoDB update operator. The connector adds the leading $ to each operator name automatically: writing set produces $set on the wire. All fields are optional. The record is open, so any additional MongoDB update operator can be passed and will likewise receive the $ prefix.

FieldMongoDB operatorDescription
set$setSet field values.
unset$unsetRemove fields.
inc$incIncrement numeric values.
mul$mulMultiply numeric values.
min$minUpdate only if the new value is less than the existing value.
max$maxUpdate only if the new value is greater than the existing value.
rename$renameRename a field.
currentDate$currentDateSet a field to the current date or timestamp.
setOnInsert$setOnInsertSet a field only when the operation results in an insert (used with upsert: true).

UpdateResult

FieldTypeDescription
matchedCountintNumber of documents matched by the filter.
modifiedCountintNumber of documents whose contents actually changed.
upsertedIdstring?Optional. Set only when an upsert occurred and a new _id was assigned. Absent from the result otherwise.

DeleteResult

FieldTypeDescription
deletedCountintNumber of documents deleted.
acknowledgedbooleanWhether the operation was acknowledged by the server.

Index

FieldTypeDescription
nsstringIndex namespace (<database>.<collection>).
vintIndex version.
namestringIndex name.
keymap<json>Index key specification.

Index is an open record. Servers may include additional fields (unique, sparse, weights, etc.) depending on the index type.