Skip to content

Martini MongoDB Functions

Overview

Martini MongoDB Functions (MongoDbMethods) let your workflows and services query, insert, and manage MongoDB data directly from Groovy scripts or Function nodes, without hand-rolling MongoDB driver code. These functions cover common data-access patterns — finding documents, inserting single or bulk documents, listing collection indexes, and running map-reduce jobs — while returning results as data models or cursors that fit naturally into your workflow or service.

Reach for these functions when a MongoDB service or the MongoDB Database Node doesn't cover your use case — for example, when you need bulk write operations, index inspection, map-reduce aggregation, or other logic that isn't exposed by those visual, query-driven tools.

What You Will Learn

  • How to query MongoDB documents with find and findFirst
  • How to insert one or many documents with insertOne, insertMany, and bulkWrite
  • What the collectionName, ordered, bypassDocumentValidation, closeClient, and resultClass parameters control, and on which methods they appear
  • How to inspect collection indexes with listIndexes and aggregate data with mapReduce
  • How to access the underlying codec registry for advanced Groovy usage with getDataModelCodecRegistry

When To Use This

Use MongoDB Functions when you need to:

  • Read one or more documents from a MongoDB collection as part of a workflow or service, using a query filter and optional projection
  • Insert one document or a batch of documents into a collection, including controlling ordering and validation behavior
  • Perform a bulk write of mixed insert/update/delete operations in a single round trip
  • Inspect the indexes defined on a collection before running a query that depends on them
  • Run a map-reduce aggregation against a collection
  • Write advanced Groovy code that needs direct access to the MongoDB codec registry used to convert between MongoDB documents and Martini data models

Prerequisites


Querying Documents with find and findFirst

find opens a Martini cursor that converts matching MongoDB documents into data models one at a time, so you can iterate over a large result set without loading every document into memory at once. findFirst runs the same kind of query but returns only the first matching document (or null if there is no match), which is useful when you only need a single record.

Both functions accept either a connectionName (the name of a configured MongoDB connection) or a pre-configured client (a MongoClient instance that already includes the data model codec — see Advanced Codec Access with getDataModelCodecRegistry).

Parameters

Parameter Required (non-nullable) Description
connectionName / client Yes The name of the MongoDB connection to use, or a pre-configured MongoClient.
databaseName Yes The name of the database to query.
collection Yes The name of the collection to query.
filter No The selection filter, using MongoDB query operators. Leave null to match all documents.
projection No Specifies which fields to return in the matched documents. Leave null to return full documents.
clientSession No The client session to associate with this operation. Leave null if there is no session.
closeClient No If true, the MongoDB client is closed after the cursor is exhausted. Defaults to false.

Return Value

  • find returns a cursor-backed data model (mongoFindCursor) that your workflow or service iterates over one document at a time.
  • findFirst returns a data model representing the first matching document (mongoResult), or null if no document matches the filter.
1
2
3
4
5
6
7
8
// Find the first active customer document
def customer = findFirst(
    connectionName: 'mongoConnection',
    databaseName: 'salesDb',
    collection: 'customers',
    filter: '{ "status": "active" }',
    closeClient: false
)

Inserting Documents with insertOne, insertMany, and bulkWrite

Use insertOne to insert a single document, insertMany to insert a batch of documents in one call, and bulkWrite when you need to combine inserts, updates, and deletes into a single MongoDB round trip. A call to insertMany is equivalent to a call to bulkWrite with only insert operations.

insertMany is also available as a cursor-based function: it opens a write-only cursor that converts data models written to it into MongoDB documents, letting you stream documents into a collection instead of supplying them all up front as a List.

Common Parameters Across Insert and Write Methods

The following parameters appear across insertOne, insertMany, and bulkWrite. Confirm the exact parameter set for each overload against the function reference in Martini Designer's content assist, since the cursor and list-based overloads differ slightly.

Parameter Required (non-nullable) Description
connectionName Yes The name of the MongoDB connection to use.
databaseName Yes The name of the database containing the collection.
collectionName Yes The name of the collection in the database.
clientSession No The client session to associate with this operation. Leave null if there is no session.
documents Yes (for insertMany) The list of documents to insert.
ordered No If true, documents are inserted in order and insertion stops on the first error; if false, all documents are attempted regardless of errors. Defaults to false.
bypassDocumentValidation No If true, the insert bypasses the collection's document validation rules.
batchSize No The batch size used when writing documents through the cursor-based insertMany. Defaults to 10000.
closeClient No If true, the MongoDB client is closed after the cursor is exhausted. Defaults to false.
1
2
3
4
5
6
7
8
9
// Insert a batch of documents, stopping on the first error
insertMany(
    connectionName: 'mongoConnection',
    databaseName: 'salesDb',
    collectionName: 'customers',
    documents: customerDocuments,
    ordered: true,
    bypassDocumentValidation: false
)

Retryable writes

insertMany supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites connection setting is enabled. For bulkWrite, only batches composed of retryable single-document operations are retried; batches containing operations such as updateMany or deleteMany are not retryable.

Inspecting Indexes with listIndexes

listIndexes returns the indexes defined on a collection, which is useful for confirming a query is backed by the expected index before you rely on it for performance.

Parameter Required (non-nullable) Description
connectionName Yes The name of the MongoDB connection to use.
databaseName Yes The name of the database containing the collection.
collectionName Yes The name of the collection in the database.
clientSession No The client session to associate with this operation. Leave null if there is no session.
closeClient No If true, the MongoDB client is closed after the cursor is exhausted. Defaults to false.
1
2
3
4
5
6
7
// List the indexes defined on the customers collection
def indexes = listIndexes(
    connectionName: 'mongoConnection',
    databaseName: 'salesDb',
    collectionName: 'customers',
    closeClient: false
)

Aggregating Data with mapReduce

mapReduce runs a map-reduce operation against a collection, letting you aggregate large datasets on the server instead of pulling every document into your workflow or service.

Parameter Required (non-nullable) Description
connectionName Yes The name of the MongoDB connection to use.
databaseName Yes The name of the database containing the collection.
collectionName Yes The name of the collection in the database.
mapFunction Yes The JavaScript map function.
reduceFunction Yes The JavaScript reduce function.
clientSession No The client session to associate with this operation. Leave null if there is no session.
resultClass No The class into which each result document is cast. Use Document.class for generic results.
closeClient No If true, the MongoDB client is closed after the cursor is exhausted. Defaults to false.

Confirm the exact parameter set for mapReduce in Martini Designer's Function content assist before relying on additional optional parameters (such as a query filter or sort/limit), since these vary by MongoDB driver version.

Advanced Codec Access with getDataModelCodecRegistry

getDataModelCodecRegistry returns the CodecRegistry that Martini uses to convert MongoDB documents to and from data models. It is intended for advanced Groovy usage — for example, constructing your own MongoClient (to pass to the client overloads of find and findFirst) that still understands Martini data models.

This method is hidden from Martini Designer's generated Function browsing; it is only reachable from Groovy code, since typical workflow and service nodes never need to touch the codec registry directly.

1
2
3
4
5
6
7
8
import com.mongodb.MongoClientSettings
import com.mongodb.client.MongoClients

def registry = MongoDbMethods.getDataModelCodecRegistry()
def settings = MongoClientSettings.builder()
    .codecRegistry(registry)
    .build()
def client = MongoClients.create(settings)

Troubleshooting

Use this table to quickly diagnose common MongoDB Function failures in Martini Designer and runtime logs.

Problem Detection Cause Fix
MongoDB connection cannot be resolved Runtime or Console logs show a connection-not-found error for connectionName The connectionName passed to find, insertMany, or other methods does not match a MongoDB database connection configured in Martini runtime Verify the MongoDB database connection name in runtime configuration, then update the function call to use the exact same connectionName
Function call shows a Designer validation error for connectionName Martini Designer marks the function call as an error because connectionName is missing The required connectionName input was left empty in the function call configuration Set connectionName to a configured MongoDB database connection name, then save and run again
Codec conversion fails for custom document classes Logs include a codec configuration error (for example, a codec cannot be found for a class) The custom MongoClient codec registry does not include Martini's data model codec registry Build the client with MongoDbMethods.getDataModelCodecRegistry() and pass that client to the client overload

Helpful Resources