Camel Components

MongoDB

Since Camel 2.19

Both producer and consumer are supported

According to Wikipedia: "NoSQL is a movement promoting a loosely defined class of non-relational data stores that break with a long history of relational databases and ACID guarantees." NoSQL solutions have grown in popularity in the last few years, and major extremely used sites and services such as Facebook, LinkedIn, Twitter, etc. are known to use them extensively to achieve scalability and agility.

Basically, NoSQL solutions differ from traditional RDBMS (Relational Database Management Systems) in that they don’t use SQL as their query language and generally don’t offer ACID-like transactional behaviour nor relational data. Instead, they are designed around the concept of flexible data structures and schemas (meaning that the traditional concept of a database table with a fixed schema is dropped), extreme scalability on commodity hardware and blazing-fast processing.

MongoDB is a very popular NoSQL solution. The camel-mongodb component integrates Camel with MongoDB, allowing you to interact with MongoDB collections both as a producer (performing operations on the collection) and as a consumer (consuming documents from a MongoDB collection).

MongoDB revolves around the concepts of documents (not as is office documents, but rather hierarchical data defined in JSON/BSON) and collections. This component page will assume you are familiar with them. Otherwise, visit http://www.mongodb.org/.

The MongoDB Camel component uses Mongo Java Driver 4.x.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-mongodb</artifactId>
    <version>x.y.z</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI formats

mongodb:connectionBean?database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
mongodb:dummy?hosts=hostnames&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
mongodb:dummy?connectionUriString=RAW(mongodb://host:port)&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]

The endpoint uses the first client it finds in this order:

  1. the client set with the mongoConnection endpoint option

  2. a client the endpoint creates from the connectionUriString or hosts option

  3. the mongoConnection client of the component, which is autowired when the registry holds exactly one MongoClient

  4. the MongoClient bean named by the endpoint path (connectionBean)

A client the endpoint creates from connectionUriString or hosts belongs to that endpoint: each such endpoint has its own client and connection pool, and closes it when it stops (for example when its route is removed or reloaded, or when the CamelContext stops). The endpoint never closes a client it did not create. To share one client between endpoints, bind a MongoClient and have the endpoints use it instead of connectionUriString or hosts.

Client options

The client options of the endpoint (replicaSet, readPreference, readPreferenceTags, maxStalenessSeconds, appName, compressors, zlibCompressionLevel, connectTimeoutMS, socketTimeoutMS, serverSelectionTimeoutMS, localThresholdMS, heartbeatFrequencyMS, maxIdleTimeMS, maxLifeTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS, srvServiceName, srvMaxHosts, retryWrites, retryReads, directConnection and loadBalanced) configure the client the endpoint creates from hosts or connectionUriString. For example, a tailable consumer that reads from the secondaries of a replica set:

mongodb:dummy?hosts=host1:27017,host2:27017,host3:27017&replicaSet=rs0&readPreference=SECONDARY&database=shop&collection=events&consumerType=tailable&tailTrackIncreasingField=seq

An option is applied only when its value differs from its default, and then it overrides the same option in connectionUriString. An option left at its default keeps the value of the connection string, so connectionUriString=RAW(mongodb://host/?readPreference=nearest) reads from the nearest member. The read preference is made of readPreference, readPreferenceTags and maxStalenessSeconds together: when any of them is set, the three replace the read preference of the connection string.

These options cannot change a MongoClient the endpoint did not create (set with mongoConnection, on the component, or from the registry). Configure such a client with its own MongoClientSettings. In that case the endpoint logs a WARN that lists the options it does not use.

The org.apache.camel.component.mongodb.SslAwareMongoClient client, which the MongoDB Kamelets create as a bean, has the properties hosts, username, password (of a user defined in the admin database), ssl, sslValidationEnabled and readPreference (the same values as the endpoint option). The username and password are given as they are: the client percent-encodes them.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The MongoDB component supports the following options which are listed below.

Name Description Default Type

mongoConnection (common)

Autowired Shared client used for connection. All endpoints generated from the component will share this connection client, except the endpoints that set hosts or connectionUriString, which create their own client.

MongoClient

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

Endpoint Options

The MongoDB endpoint is configured using URI syntax:

mongodb:connectionBean

With the following path and query parameters:

Path Parameters

Name Description Default Type

connectionBean (common)

Required The name of the MongoClient bean to look up in the registry, used when neither hosts nor connectionUriString is set.

String

Query Parameters

Name Description Default Type

collection (common)

The name of the collection. Required, except for the getDbStats and command operations.

String

collectionIndex (common)

The indexes to create on the collection when the endpoint starts, as a JSON object that maps each field name to its index type, such as 1 (ascending) or -1 (descending). Each field gets an index of its own.

String

connectionUriString (common)

The whole MongoDB connection string of the endpoint. When set, the endpoint creates its client from it, instead of using the client of the component or the connectionBean.

String

createCollection (common)

Whether the endpoint may use a collection that does not exist yet: MongoDB then creates it on the first write. When false, the producer fails to start if the collection does not exist. The consumer always needs an existing collection.

true

boolean

database (common)

The name of the database.

String

hosts (common)

Host address of mongodb server in [host]:[port] format. It’s possible to also use more than one address, as a comma separated list of hosts: [host1]:[port1],[host2]:[port2]. If this parameter is specified, the provided connectionBean is ignored.

String

mongoConnection (common)

The MongoClient the endpoint uses, instead of creating a client or looking one up.

MongoClient

operation (common)

The operation the producer runs. The CamelMongoDbOperation header overrides it.

Enum values:

  • findById

  • findOneAndDelete

  • findOneAndReplace

  • findOneAndUpdate

  • findOneByQuery

  • findAll

  • findDistinct

  • insert

  • save

  • update

  • remove

  • bulkWrite

  • aggregate

  • getDbStats

  • getColStats

  • count

  • command

MongoDbOperation

outputType (common)

The type of the result of the findAll and aggregate operations: MongoIterable gives the iterable of the driver (the query runs when the body is iterated), DocumentList (or no value) gives a List of the documents. Document has no effect.

Enum values:

  • DocumentList

  • Document

  • MongoIterable

MongoDbOutputType

changeStreamToken (consumer)

A resume token of the change stream, as JSON text, that the change streams consumer resumes after when it starts. It takes precedence over the token stored in changeStreamTokenRepository.

String

changeStreamTokenRepository (consumer)

The state repository where the change streams consumer stores the resume token of the last change it routed (under the key routeId/collection), to resume after it when it starts again.

StateRepository

consumerType (consumer)

The type of the consumer: tailable (a tailable cursor on a capped collection) or changeStreams (a change stream of the collection).

Enum values:

  • tailable

  • changeStreams

tailable

String

fullDocument (consumer)

Whether the change events of updates contain the full document: default (no), updateLookup (the current version of the document), whenAvailable (the document after the update, when the collection records it) or required (the same, and an error when it is not available). The full document is the message body.

Enum values:

  • default

  • updateLookup

  • required

  • whenAvailable

default

FullDocument

persistentId (consumer)

The id of the tail tracking document of this consumer in the tail tracking collection. Set it when persistentTailTracking is enabled, and give each consumer that shares the collection its own id.

String

persistentTailTracking (consumer)

Whether the tailable consumer stores the last value of tailTrackIncreasingField in the tail tracking collection, so that after a restart it goes on after the last document it routed instead of from the start of the collection.

false

boolean

tailTrackCollection (consumer)

The collection that stores the tail tracking documents. Defaults to camelTailTracking.

String

tailTrackDb (consumer)

The database of the tail tracking collection. Defaults to the database of the endpoint.

String

tailTrackField (consumer)

The field of the tail tracking document that stores the last tracked value. Defaults to lastTrackingValue.

String

tailTrackIncreasingField (consumer)

The field of the documents whose value increases with each insert, such as a sequence number or a timestamp. The tailable consumer keeps the value of the last document it routed, and opens a new cursor on the documents whose field is greater than that value. It must be a top-level field of the document (dot notation is not supported).

String

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

appName (advanced)

The name of the application, which the driver sends to the server, where it shows in the server logs, the slow query logs and the profile collection.

String

compressors (advanced)

The compression algorithms the driver offers the server for the messages between them, as a comma-separated list in order of preference: zlib, snappy or zstd. snappy and zstd need the snappy-java and zstd-jni libraries.

String

connectTimeoutMS (advanced)

Specifies the maximum amount of time, in milliseconds, the Java driver waits for a connection to open before timing out. A value of 0 instructs the driver to never time out while waiting for a connection to open. Default: 10000 (10 seconds).

10000

Integer

cursorRegenerationDelay (advanced)

The time to wait before the consumer opens a new cursor, after the server closed the previous one or opening it failed. 0 opens the new cursor at once.

1000

long

directConnection (advanced)

Whether the driver connects directly to the single host given, instead of discovering the members of the replica set or sharded cluster. Cannot be used with several hosts.

false

boolean

dynamicity (advanced)

Whether the producer reads the database and the collection from the CamelMongoDbDatabase and CamelMongoDbCollection headers, which then override the database and collection options. Off by default.

false

boolean

heartbeatFrequencyMS (advanced)

The interval, in milliseconds, between the checks of the state of each server of the deployment, counted from the end of one check to the start of the next. The driver default is 10000 (10 seconds).

Integer

loadBalanced (advanced)

Whether the driver connects to MongoDB through a load balancer, given as the single host. Takes precedence over directConnection.

false

boolean

localThresholdMS (advanced)

The size, in milliseconds, of the latency window for choosing among several suitable servers: only the servers whose round-trip time is within this window of the fastest one are chosen.

15

Integer

maxConnecting (advanced)

The maximum number of connections the connection pool may be opening at the same time.

2

Integer

maxIdleTimeMS (advanced)

The time, in milliseconds, a pooled connection may stay idle before the driver closes it. 0 means no limit.

0

Integer

maxLifeTimeMS (advanced)

The time, in milliseconds, the driver may keep a pooled connection open before it closes it. 0 means no limit.

0

Integer

maxPoolSize (advanced)

The maximum number of connections of the connection pool.

100

Integer

maxStalenessSeconds (advanced)

How stale, in seconds, a secondary may be before the driver stops reading from it. The minimum is 90 seconds, or the heartbeat frequency plus 10 seconds if that is greater. -1 means no staleness check. Needs a readPreference other than PRIMARY.

-1

Integer

minPoolSize (advanced)

The minimum number of connections the connection pool keeps open.

0

Integer

readPreference (advanced)

How the driver routes read operations to the members of a replica set: PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED or NEAREST.

Enum values:

  • PRIMARY

  • PRIMARY_PREFERRED

  • SECONDARY

  • SECONDARY_PREFERRED

  • NEAREST

PRIMARY

String

readPreferenceTags (advanced)

A representation of a tag set as a comma-separated list of colon-separated key-value pairs, e.g. dc:ny,rack:1. Spaces are stripped from the beginning and end of all keys and values. To specify a list of tag sets, separate them with semicolons, e.g. dc:ny,rack:1;dc:ny; (the form dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= of a connection string is accepted too). Note the empty tag set at the end, which means match any secondary as a last resort. Order matters when using multiple tag sets. The tag sets need a readPreference other than PRIMARY.

String

replicaSet (advanced)

The name of the replica set. The driver connects only to members of a replica set with this name, and discovers the other members from the hosts given.

String

retryReads (advanced)

Specifies that the driver must retry supported read operations if they fail due to a network error. Default: true.

true

boolean

retryWrites (advanced)

Specifies that the driver must retry supported write operations if they fail due to a network error. Default: true.

true

boolean

serverSelectionTimeoutMS (advanced)

How long, in milliseconds, the driver waits to find a suitable server for an operation before it throws an exception.

30000

Integer

socketTimeoutMS (advanced)

The time, in milliseconds, the driver waits for a read from a socket before it times out. 0 means no timeout.

0

Integer

srvMaxHosts (advanced)

The maximum number of hosts from the SRV DNS records the driver connects to. 0 means no limit. Only used with a mongodb+srv connection string.

Integer

srvServiceName (advanced)

The service name of the SRV DNS records the driver looks up to find the hosts. Only used with a mongodb+srv connection string.

mongodb

String

waitQueueTimeoutMS (advanced)

The time, in milliseconds, a thread waits for a connection of the pool to become available.

120000

Integer

writeConcern (advanced)

The write concern of the producer: the acknowledgment it requests from MongoDB for write operations. ACKNOWLEDGED uses the default write concern of the server. Possible values are ACKNOWLEDGED, W1, W2, W3, UNACKNOWLEDGED, JOURNALED or MAJORITY.

Enum values:

  • ACKNOWLEDGED

  • W1

  • W2

  • W3

  • UNACKNOWLEDGED

  • JOURNALED

  • MAJORITY

ACKNOWLEDGED

String

writeResultAsHeader (advanced)

For the insert, save, update and remove operations: keep the message body, and put the result of the operation in the CamelMongoWriteResult header instead of the body.

false

boolean

zlibCompressionLevel (advanced)

The zlib compression level, from -1 to 9: lower values compress faster, higher values compress smaller, -1 is the default level of zlib. Only used when zlib is one of the compressors.

Integer

streamFilter (changeStream)

A JSON document with one aggregation pipeline stage, such as a $match, that the change stream applies to the change events.

String

authSource (security)

The name of the database that holds the credentials of the user (the authentication database).

String

password (security)

The password to authenticate with.

String

sslContextParameters (security)

SSL configuration using a Camel SSLContextParameters object. When configured, TLS is automatically enabled on the connection.

SSLContextParameters

tls (security)

Specifies that all communication with MongoDB instances should use TLS. Supersedes the ssl option. Applies to the client the endpoint creates from hosts or connectionUriString. Default: false.

false

boolean

tlsAllowInvalidHostnames (security)

Specifies that the driver should allow invalid hostnames in the certificate for TLS connections. Supersedes sslInvalidHostNameAllowed. Has the same effect as tlsInsecure by setting tlsAllowInvalidHostnames to true. Default: false.

false

boolean

username (security)

The username to authenticate with.

String

Message Headers

The MongoDB component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelMongoDbOperation (producer)

Constant: OPERATION_HEADER

The operation to run, instead of the operation option.

MongoDbOperation or String

CamelMongoDbResultTotalSize (producer findAll)

Constant: RESULT_TOTAL_SIZE

Set by the findById and findOneByQuery operations: 1 when they found a document, 0 otherwise.

Integer

CamelMongoDbResultPageSize (producer findAll)

Constant: RESULT_PAGE_SIZE

The number of documents that findAll or aggregate returned in a List (not with outputType=MongoIterable), or the number of values that findDistinct returned.

Integer

CamelMongoDbCriteria (producer)

Constant: CRITERIA

The query filter of the findAll, findOneByQuery, count, update, findOneAndUpdate and findOneAndReplace operations, instead of the body (update and findOneAndUpdate then take the update from the body). For save, it is combined with the filter on the _id, for example to give the shard key.

Bson

CamelMongoDbFieldsProjection (producer)

Constant: FIELDS_PROJECTION

The projection: the fields of the documents that the find operations return.

Bson

CamelMongoDbBatchSize (producer findAll aggregate)

Constant: BATCH_SIZE

The number of documents per batch that the server returns.

Integer

CamelMongoDbNumToSkip (producer findAll)

Constant: NUM_TO_SKIP

The number of documents that findAll skips.

Integer

CamelMongoDbMultiUpdate (producer update)

Constant: MULTIUPDATE

Whether the update operation updates all the documents that match the filter, instead of the first one.

Boolean

CamelMongoDbUpsert (producer update)

Constant: UPSERT

Whether the update, findOneAndUpdate and findOneAndReplace operations insert a document when none matches the filter.

Boolean

CamelMongoDbRecordsAffected (producer)

Constant: RECORDS_AFFECTED

The number of documents that update modified or remove deleted.

long

CamelMongoDbRecordsMatched (producer)

Constant: RECORDS_MATCHED

The number of documents that matched the filter of update.

long

CamelMongoDbSortBy (producer)

Constant: SORT_BY

The sort order of the findAll, findOneByQuery, findOneAndDelete, findOneAndReplace and findOneAndUpdate operations.

Document

CamelMongoDbDatabase (common)

Constant: DATABASE

The name of the database. The producer uses it instead of the database option when dynamicity is enabled. The consumer sets it to the database of the endpoint.

String

CamelMongoDbCollection (common)

Constant: COLLECTION

The name of the collection. The producer uses it instead of the collection option when dynamicity is enabled. The consumer sets it to the collection of the endpoint.

String

CamelMongoDbCollectionIndex (producer)

Constant: COLLECTION_INDEX

The indexes to create on the collection of the CamelMongoDbCollection header, instead of those of collectionIndex. Used only when dynamicity is enabled.

List

CamelMongoDbLimit (producer findAll)

Constant: LIMIT

The maximum number of documents that findAll returns.

Integer

CamelMongoDbTailable (consumer)

Constant: FROM_TAILABLE

Set to true by the consumer on the messages it creates.

Boolean

CamelMongoWriteResult (producer)

Constant: WRITERESULT

The result of the insert, save, update or remove operation, when writeResultAsHeader is enabled.

Object

CamelMongoOid (producer)

Constant: OID

The _id of the document that insert or save wrote, or a List of the _id values when insert wrote a List of documents.

Object or List

CamelMongoDbDistinctQueryField (producer)

Constant: DISTINCT_QUERY_FIELD

The name of the field whose distinct values findDistinct returns.

String

CamelMongoDbAllowDiskUse (producer findAll aggregate)

Constant: ALLOW_DISK_USE

Whether the server may write temporary files to disk for the findAll, findById, findOneByQuery and aggregate operations (allowDiskUse). The find operations need MongoDB 4.4 or later for it.

Boolean

CamelMongoDbBulkOrdered (producer bulkWrite)

Constant: BULK_ORDERED

Whether bulkWrite runs the writes in order and stops at the first error (true), or in any order and goes on after an error (false).

TRUE

Boolean

_id (consumer changeStreams)

Constant: MONGO_ID

The _id of the document created or modified by the insert, replace, delete or update operation (i.e. CRUD operations). It is an org.bson.types.ObjectId when MongoDB generated the id, and otherwise the id in its natural Java type: a String, a number, or a Document for a compound key. The header is absent on the events that do not belong to a single document, such as invalidate, drop, rename and dropDatabase.

Object

CamelMongoDbStreamOperationType (consumer changeStreams)

Constant: STREAM_OPERATION_TYPE

The type of operation that occurred. Can be any of the following values: insert, delete, replace, update, drop, rename, dropDatabase, invalidate.

String

CamelOffset (consumer changeStreams)

Constant: OFFSET

The position of the event in the change stream, as an org.apache.camel.resume.Resumable whose key is the route ID and the collection, and whose offset is the resume token of the event in JSON. Set on each event that has a resume token, for the resumable EIP to store the position.

Resumable

CamelMongoDbReturnDocumentType (producer update one and return)

Constant: RETURN_DOCUMENT

Whether findOneAndUpdate and findOneAndReplace return the document as it was before the change (BEFORE, the default) or after it (AFTER).

Enum values:

  • BEFORE

  • AFTER

ReturnDocument

CamelMongoDbOperationOption (producer update one and options)

Constant: OPTIONS

The options of the driver for findOneAndUpdate, findOneAndReplace or findOneAndDelete (FindOneAndUpdateOptions, FindOneAndReplaceOptions or FindOneAndDeleteOptions). When set, the CamelMongoDbUpsert, CamelMongoDbSortBy, CamelMongoDbFieldsProjection and CamelMongoDbReturnDocumentType headers are ignored.

Object

Message Body

The message body at each side of the MongoDB component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

pojo (org.bson.Document)

The document added to the capped collection; with changeStreams the full document of the change, null when the change has none (an update without fullDocument=updateLookup).

  • With consumerType=changeStreams: pojo or null

Producer input

any

A document or a query: a Document, a Map or JSON text; a List of them for insert, aggregate and update.

Producer output

unknown

By the operation: a Document or null for a find of one, a List for findAll, findDistinct and aggregate, a Long for count, the document added for insert, the result of the driver for the other writes, and a Document for command and the stats.

  • With operation=findById: pojo or null (org.bson.Document)

  • With operation=findOneByQuery: pojo or null (org.bson.Document)

  • With operation=findOneAndDelete: pojo or null (org.bson.Document)

  • With operation=findOneAndReplace: pojo or null (org.bson.Document)

  • With operation=findOneAndUpdate: pojo or null (org.bson.Document)

  • With operation=findAll: list

  • With operation=findDistinct: list

  • With operation=aggregate: list

  • With operation=count: value (java.lang.Long)

  • With operation=insert: pojo or list

  • With operation=save: pojo

  • With operation=update: pojo (com.mongodb.client.result.UpdateResult)

  • With operation=remove: pojo (com.mongodb.client.result.DeleteResult)

  • With operation=bulkWrite: pojo (com.mongodb.bulk.BulkWriteResult)

  • With operation=command: pojo (org.bson.Document)

  • With operation=getDbStats: pojo (org.bson.Document)

  • With operation=getColStats: pojo (org.bson.Document)

Not known when outputType or writeResultAsHeader is set.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Deterministic simulation tests

The consumer of the MongoDB component is tested with deterministic simulation tests: the real consumer runs under a seeded virtual-time scheduler against a fake of the external system, which injects faults while the tests check invariants. A failing seed can be replayed. These are the fake worlds of the component:

World What it checks Issues

MongoDbChangeStreamsWorld

Fake: FakeMongo: a MongoDB collection and its change stream (resumeAfter, startAfter, drop and invalidate events, the resume of the driver), behind the MongoClient of the connectionBean option

Tests: MongoDbChangeStreamsDstTest

Covers:

  • the change streams consumer with a store of its resume token (changeStreamTokenRepository)

  • a dropped collection, made again by an insert

  • a server that cannot be reached for a while: the cursor cannot be opened, a getMore fails

  • route restarts (the consumer thread interrupted, then the route stopped and started), resuming after the stored token

  • the fullDocument option and cursorRegenerationDelay

Faults:

  • the collection is dropped

  • the server cannot be reached

  • a getMore fails

  • the server answers slowly

  • processing fails

  • processing is slow

Invariants:

  • the consumer uses the client as documented

  • the route starts once the collection exists and the server can be reached

  • the consumer thread runs as long as the route is started

  • a resume token is stored only after its exchange completed

  • a stored resume token never passes an event that was not routed

  • every exchange carries a resume token

  • every event is routed once the faults cleared

The worlds and their tests are in the test sources of the component. How to run them, replay a seed and write a world is described in Running the tests and Writing a fake world.

Usage

Configuration of a database in Spring XML

The following Spring XML creates a bean defining the connection to a MongoDB instance.

Since mongo java driver 3, the WriteConcern and readPreference options have not been dynamically modifiable. They are defined in the mongoClient object:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">

  <mongo:mongo-client id="mongoBean" host="${mongo.url}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pass}@${mongo.dbname}">
    <mongo:client-options write-concern="NORMAL" />
  </mongo:mongo-client>
</beans>

MongoDB operations - producer endpoints

Query operations

findById

This operation retrieves only one element from the collection whose _id field matches the content of the IN message body. The incoming object can be anything that has an equivalent to a Bson type. See http://bsonspec.org/spec.html and http://www.mongodb.org/display/DOCS/Java+Types.

  • Java

  • XML

  • YAML

from("direct:findById")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findById")
    .to("mock:resultFindById");
<route>
  <from uri="direct:findById"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=findById"/>
  <to uri="mock:resultFindById"/>
</route>
- route:
    from:
      uri: direct:findById
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: findById
        - to:
            uri: mock:resultFindById

Please note that the default _id is treated by Mongo as and ObjectId type, so you may need to convert it properly.

  • Java

  • XML

  • YAML

from("direct:findById")
    .convertBodyTo(ObjectId.class)
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findById")
    .to("mock:resultFindById");
<route>
  <from uri="direct:findById"/>
  <convertBodyTo type="org.bson.types.ObjectId"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=findById"/>
  <to uri="mock:resultFindById"/>
</route>
- route:
    from:
      uri: direct:findById
      steps:
        - convertBodyTo:
            type: org.bson.types.ObjectId
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: findById
        - to:
            uri: mock:resultFindById

Supports optional parameters

This operation supports projection operators. See Specifying a fields filter (projection).

findOneByQuery

Retrieve the first element from a collection matching a MongoDB query selector. If the CamelMongoDbCriteria header is set, then its value is used as the query selector. If the CamelMongoDbCriteria header is null, then the IN message body is used as the query selector. In both cases, the query selector should be of type Bson or convertible to Bson (for instance, a JSON string or HashMap). See Type conversions for more info.

Create query selectors using the Filters provided by the MongoDB Driver.

Example without a query selector (returns the first document in a collection)
  • Java

  • XML

  • YAML

from("direct:findOneByQuery")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery")
    .to("mock:resultFindOneByQuery");
<route>
  <from uri="direct:findOneByQuery"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=findOneByQuery"/>
  <to uri="mock:resultFindOneByQuery"/>
</route>
- route:
    from:
      uri: direct:findOneByQuery
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: findOneByQuery
        - to:
            uri: mock:resultFindOneByQuery
Example with a query selector (returns the first matching document in a collection):
Java-only: requires Bson Filters object
from("direct:findOneByQuery")
    .setHeader("CamelMongoDbCriteria", constant(Filters.eq("name", "Raul Kripalani")))
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery")
    .to("mock:resultFindOneByQuery");

Supports optional parameters

This operation supports projection operators and sort clauses. See Specifying a fields filter (projection), Specifying a sort clause.

findAll

The findAll operation returns all documents matching a query, or none at all, in which case all documents contained in the collection are returned. The query object is extracted CamelMongoDbCriteria header. if the CamelMongoDbCriteria header is null the query object is extracted message body, i.e., it should be of type Bson or convertible to Bson. It can be a JSON String or a Hashmap. See Type conversions for more info.

Example without a query selector (returns all documents in a collection)
  • Java

  • XML

  • YAML

from("direct:findAll")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
    .to("mock:resultFindAll");
<route>
  <from uri="direct:findAll"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=findAll"/>
  <to uri="mock:resultFindAll"/>
</route>
- route:
    from:
      uri: direct:findAll
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: findAll
        - to:
            uri: mock:resultFindAll
Example with a query selector (returns all matching documents in a collection)
Java-only: requires Bson Filters object
from("direct:findAll")
    .setHeader("CamelMongoDbCriteria", constant(Filters.eq("name", "Raul Kripalani")))
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
    .to("mock:resultFindAll");
Example with option outputType=MongoIterable and batch size
Java-only: requires Bson Filters object
from("direct:findAll")
    .setHeader("CamelMongoDbBatchSize", constant(10))
    .setHeader("CamelMongoDbCriteria", constant(Filters.eq("name", "Raul Kripalani")))
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll&outputType=MongoIterable")
    .to("mock:resultFindAll");

Supports optional parameters

This operation supports projection operators and sort clauses. See Specifying a fields filter (projection), Specifying a sort clause.

count

Returns the total number of objects in a collection, returning a Long as the OUT message body.
The following example will count the number of records in the "dynamicCollectionName" collection. Notice how dynamicity is enabled, and as a result, the operation will not run against the "notableScientists" collection, but against the "dynamicCollectionName" collection.

  • Java

  • XML

  • YAML

from("direct:count")
    .to("mongodb:myDb?database=tickets&collection=flights&operation=count&dynamicity=true");
<route>
  <from uri="direct:count"/>
  <to uri="mongodb:myDb?database=tickets&amp;collection=flights&amp;operation=count&amp;dynamicity=true"/>
</route>
- route:
    from:
      uri: direct:count
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: tickets
              collection: flights
              operation: count
              dynamicity: true

To dynamically target a different collection, set the CamelMongoDbCollection header:

Java-only: Java test API (ProducerTemplate)
Long result = template.requestBodyAndHeader("direct:count", "irrelevantBody",
        "CamelMongoDbCollection", "dynamicCollectionName");

You can provide a query The query object is extracted CamelMongoDbCriteria header. if the CamelMongoDbCriteria header is null the query object is extracted message body, i.e., it should be of type Bson or convertible to Bson., and operation will return the number of documents matching the criteria.

Java-only: Java test API (ProducerTemplate)
Document query = ...
Long count = template.requestBodyAndHeader("direct:count", query,
        "CamelMongoDbCollection", "dynamicCollectionName");
Specifying a fields filter (projection)

Query operations will, by default, return the matching objects in their entirety (with all their fields). If your documents are large, and you only require retrieving a subset of their fields, you can specify a field filter in all query operations, simply by setting the relevant Bson (or type convertible to Bson, such as a JSON String, Map, etc.) on the CamelMongoDbFieldsProjection header.

Here is an example that uses MongoDB’s Projections to simplify the creation of Bson. It retrieves all fields except _id and boringField:

Java-only: Java test API with Bson Projection
// route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
Bson fieldProjection = Projection.exclude("_id", "boringField");
Object result = template.requestBodyAndHeader("direct:findAll", ObjectUtils.NULL,
        "CamelMongoDbFieldsProjection", fieldProjection);
Specifying a sort clause

There is often a requirement to fetch the min/max record from a collection based on sorting by a particular field that uses MongoDB’s Sorts to simplify the creation of Bson. It retrieves all fields except _id and boringField:

Java-only: Java test API with Bson Sorts
// route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
Bson sorts = Sorts.descending("_id");
Object result = template.requestBodyAndHeader("direct:findAll", ObjectUtils.NULL,
        "CamelMongoDbSortBy", sorts);

In a Camel route, the SORT_BY header can be used with the findOneByQuery operation to achieve the same result. If the FIELDS_PROJECTION header is also specified, the operation will return a single field/value pair that can be passed directly to another component (for example, a parameterized MyBatis SELECT query). This example demonstrates fetching the temporally newest document from a collection and reducing the result to a single field, based on the documentTimestamp field:

Java-only: requires Bson Sorts and Projection objects
from("direct:someTriggeringEvent")
    .setHeader("CamelMongoDbSortBy", constant(Sorts.descending("documentTimestamp")))
    .setHeader("CamelMongoDbFieldsProjection", constant(Projection.include("documentTimestamp")))
    .setBody(constant("{}"))
    .to("mongodb:myDb?database=local&collection=myDemoCollection&operation=findOneByQuery")
    .to("direct:aMyBatisParameterizedSelect");

Create/update operations

insert

Insert a new object into the MongoDB collection, taken from the IN message body. Type conversion is attempted to turn it into Document or a List. Two modes are supported: single insert and multiple insert. For multiple insert, the endpoint will expect a List, Array or Collections of objects of any type, as long as they are - or can be converted to - Document. Example:

  • Java

  • XML

  • YAML

from("direct:insert")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=insert");
<route>
  <from uri="direct:insert"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=insert"/>
</route>
- route:
    from:
      uri: direct:insert
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: insert

Note that the new object’s _id must be unique in the collection. If you don’t specify the value, MongoDB will automatically generate one for you. But if you do specify it, and it is not unique, the insert operation will fail.

This is not a limitation of the component, but it is how things work in MongoDB for higher throughput. If you are using a custom _id, you are expected to ensure at the application level that is unique (and this is a good practice too).

OID(s) of the inserted record(s) are stored in the message header under CamelMongoOid key. The value stored is org.bson.types.ObjectId for single insert or java.util.List<org.bson.types.ObjectId> if multiple records have been inserted.

In MongoDB Java Driver 3.x the insertOne and insertMany operation return void. The Camel insert operation return the document or list of documents inserted. Note that each document is updated by a new OID if needed.

save

The save operation is equivalent to an upsert (UPdate, inSERT) operation, where the record will be updated, and if it doesn’t exist, it will be inserted, all in one atomic operation. MongoDB will perform the matching based on the _id field.

Beware that in case of an update, the object is replaced entirely and the usage of MongoDB’s $modifiers is not permitted. Therefore, if you want to manipulate the object if it already exists, you have two options:

  1. performing a query to retrieve the entire object first along with all its fields (may not be efficient), alter it inside Camel and then save it.

  2. using the update operation with $modifiers, which will execute the update at the server-side instead. You can enable the upsert flag, in which case if an insert is required, MongoDB will apply the $modifiers to the filter query object and insert the result.

If the document to be saved does not contain the _id attribute, the operation will be an insert, and the new _id created will be placed in the CamelMongoOid header.

For example:

  • Java

  • XML

  • YAML

from("direct:insert")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=save");
<route>
  <from uri="direct:insert"/>
  <to uri="mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=save"/>
</route>
- route:
    from:
      uri: direct:insert
      steps:
        - to:
            uri: mongodb:myDb
            parameters:
              database: flights
              collection: tickets
              operation: save
Java-only: Java test API (ProducerTemplate)
// route: from("direct:insert").to("mongodb:myDb?database=flights&collection=tickets&operation=save");
Document docForSave = new Document();
docForSave.put("key", "value");
Object result = template.requestBody("direct:insert", docForSave);
update

Update one or multiple records in the collection. Requires a filter query and a update rules.

You can define the filter using CamelMongoDbCriteria header as Bson and define the update rules as Bson in Body.

Update after enrich

While defining the filter by using CamelMongoDbCriteria header as Bson to query mongodb before you do update, you should notice you need to remove it from the resulting Camel exchange during aggregation if you use the enrich pattern with an aggregation strategy and then apply mongodb update. If you don’t remove this header during aggregation and/or redefine CamelMongoDbCriteria header before sending Camel exchange to mongodb producer endpoint, you may end up with invalid Camel exchange payload while updating mongodb.

The second way requires a List<Bson> as the IN message body containing exactly two elements:

  • Element 1 (index 0) ⇒ filter query ⇒ determines what objects will be affected, same as a typical query object

  • Element 2 (index 1) ⇒ update rules ⇒ how matched objects will be updated. All modifier operations from MongoDB are supported.

The body can also be a JSON array of these two documents as text: a String, a byte[], an InputStream or a stream-cached body, as a Kafka or file consumer or an HTTP request delivers it. This also makes the update usable from YAML and XML routes.

Multiupdates

By default, MongoDB will only update 1 object even if multiple objects match the filter query. To instruct MongoDB to update all matching records, set the CamelMongoDbMultiUpdate IN message header to true.

A header with key CamelMongoDbRecordsAffected will be returned with the number of records updated (from UpdateResult.getModifiedCount()).

For example, the following will update all records whose filterField field equals true by setting the value of the "scientist" field to "Darwin":

Java-only: Java test API with Bson filter and update
// route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update");
List<Bson> body = new ArrayList<>();
Bson filterField = Filters.eq("filterField", true);
body.add(filterField);
BsonDocument updateObj = new BsonDocument().append("$set", new BsonDocument("scientist", new BsonString("Darwin")));
body.add(updateObj);
Object result = template.requestBodyAndHeader("direct:update", body, "CamelMongoDbMultiUpdate", true);
Java-only: Java test API with criteria header
// route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update");
Map<String, Object> headers = new HashMap<>(2);
headers.put("CamelMongoDbMultiUpdate", true);
headers.put("CamelMongoDbCriteria", Filters.eq("filterField", true));
Bson updateObj = Updates.set("scientist", "Darwin");
Object result = template.requestBodyAndHeaders("direct:update", updateObj, headers);
Java-only: Java test API with JSON string
// route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update");
String updateObj = "[{\"filterField\": true}, {\"$set\", {\"scientist\", \"Darwin\"}}]";
Object result = template.requestBodyAndHeader("direct:update", updateObj, "CamelMongoDbMultiUpdate", true);

Delete operations

remove

Remove matching records from the collection. The IN message body will act as the removal filter query, and is expected to be of type DBObject or a type convertible to it.
The following example will remove all objects whose field 'conditionField' equals true, in the science database, notableScientists collection:

Java-only: Java test API with Bson filter
// route: from("direct:remove").to("mongodb:myDb?database=science&collection=notableScientists&operation=remove");
Bson conditionField = Filters.eq("conditionField", true);
Object result = template.requestBody("direct:remove", conditionField);

A header with key CamelMongoDbRecordsAffected is returned with type long, containing the number of records deleted (from DeleteResult.getDeletedCount()).

Bulk Write Operations

bulkWrite

Performs write operations in bulk with controls for order of execution. Requires a List<WriteModel<Document>> as the IN message body containing commands for insert, update, and delete operations.

The following example will insert a new scientist "Pierre Curie", update record with id "5" by setting the value of the "scientist" field to "Marie Curie" and delete record with id "3" :

Java-only: Java test API with WriteModel objects
// route: from("direct:bulkWrite").to("mongodb:myDb?database=science&collection=notableScientists&operation=bulkWrite");
List<WriteModel<Document>> bulkOperations = Arrays.asList(
        new InsertOneModel<>(new Document("scientist", "Pierre Curie")),
        new UpdateOneModel<>(new Document("_id", "5"),
                new Document("$set", new Document("scientist", "Marie Curie"))),
        new DeleteOneModel<>(new Document("_id", "3")));

BulkWriteResult result = template.requestBody("direct:bulkWrite", bulkOperations, BulkWriteResult.class);

By default, operations are executed in order and interrupted on the first write error without processing any remaining write operations in the list. To instruct MongoDB to continue to process remaining write operations in the list, set the CamelMongoDbBulkOrdered IN message header to false. Unordered operations are executed in parallel, and this behavior is not guaranteed.

Other operations

aggregate

Perform an aggregation with the given pipeline contained in the body. Aggregations could be long and heavy operations. Use with care.

The pipeline can be a List<Bson>, or a JSON array of its stages as text: a String, a byte[], an InputStream or a stream-cached body. For example, in YAML:

- route:
    from:
      uri: direct:aggregate
      steps:
        - setBody:
            constant: '[{"$match": {"scientist": "Darwin"}}, {"$group": {"_id": "$scientist", "count": {"$sum": 1}}}]'
        - to:
            uri: mongodb:myDb
            parameters:
              database: science
              collection: notableScientists
              operation: aggregate

In Java, with the Bson builders:

Java-only: requires Bson aggregation pipeline
// route: from("direct:aggregate").to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate");
List<Bson> aggregate = Arrays.asList(match(or(eq("scientist", "Darwin"), eq("scientist", "Einstein"))),
        group("$scientist", sum("count", 1)));
from("direct:aggregate")
    .setBody(constant(aggregate))
    .to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate")
    .to("mock:resultAggregate");

By default, a List of all results is returned. This can be heavy on memory depending on the size of the results. A safer alternative is to set your outputType=MongoIterable. The next Processor will see an iterable in the message body allowing it to step through the results one by one. Thus, setting a batch size and returning an iterable allows for efficient retrieval and processing of the result.

An example would look like:

Java-only: requires Bson aggregation pipeline
List<Bson> aggregate = Arrays.asList(match(or(eq("scientist", "Darwin"), eq("scientist", "Einstein"))),
        group("$scientist", sum("count", 1)));
from("direct:aggregate")
    .setHeader("CamelMongoDbBatchSize", constant(10))
    .setBody(constant(aggregate))
    .to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate&outputType=MongoIterable")
    .split(body())
    .streaming()
    .to("mock:resultAggregate");

Note that calling .split(body()) is enough to send the entries down the route one-by-one, however it would still load all the entries into memory first. Calling .streaming() is thus required to load data into memory by batches.

getDbStats

Equivalent of running the db.stats() command in the MongoDB shell, which displays useful statistic figures about the database.
For example:

> db.stats();
{
    "db" : "test",
    "collections" : 7,
    "objects" : 719,
    "avgObjSize" : 59.73296244784423,
    "dataSize" : 42948,
    "storageSize" : 1000058880,
    "numExtents" : 9,
    "indexes" : 4,
    "indexSize" : 32704,
    "fileSize" : 1275068416,
    "nsSizeMB" : 16,
    "ok" : 1
}

Usage example:

Java-only: Java test API (ProducerTemplate)
// from("direct:getDbStats").to("mongodb:myDb?database=flights&collection=tickets&operation=getDbStats");
Object result = template.requestBody("direct:getDbStats", "irrelevantBody");
assertTrue("Result is not of type Document", result instanceof Document);

The operation will return a data structure similar to the one displayed in the shell, in the form of a Document in the OUT message body.

getColStats

Equivalent of running the db.collection.stats() command in the MongoDB shell, which displays useful statistic figures about the collection.
For example:

> db.camelTest.stats();
{
    "ns" : "test.camelTest",
    "count" : 100,
    "size" : 5792,
    "avgObjSize" : 57.92,
    "storageSize" : 20480,
    "numExtents" : 2,
    "nindexes" : 1,
    "lastExtentSize" : 16384,
    "paddingFactor" : 1,
    "flags" : 1,
    "totalIndexSize" : 8176,
    "indexSizes" : {
        "_id_" : 8176
    },
    "ok" : 1
}

Usage example:

Java-only: Java test API (ProducerTemplate)
// from("direct:getColStats").to("mongodb:myDb?database=flights&collection=tickets&operation=getColStats");
Object result = template.requestBody("direct:getColStats", "irrelevantBody");
assertTrue("Result is not of type Document", result instanceof Document);

The operation will return a data structure similar to the one displayed in the shell, in the form of a Document in the OUT message body.

command

Run the body as a command on the database. Useful for admin operation as getting host information, replication or sharding status.

Collection parameter is not used for this operation.

Java-only: Java test API (ProducerTemplate)
// route: from("command").to("mongodb:myDb?database=science&operation=command");
DBObject commandBody = new BasicDBObject("hostInfo", "1");
Object result = template.requestBody("direct:command", commandBody);

Dynamic operations

An Exchange can override the endpoint’s fixed operation by setting the CamelMongoDbOperation header. The values supported are determined by the MongoDbOperation enumeration and match the accepted values for the operation parameter on the endpoint URI.

For example:

Java-only: Java test API (ProducerTemplate)
// from("direct:insert").to("mongodb:myDb?database=flights&collection=tickets&operation=insert");
Object result = template.requestBodyAndHeader("direct:insert", "irrelevantBody", "CamelMongoDbOperation", "count");
assertTrue("Result is not of type Long", result instanceof Long);

Consumers

There are several types of consumers:

  1. Tailable Cursor Consumer

  2. Change Streams Consumer

Both run in a thread of their own. When a consumer stops, it closes its cursor and waits for that thread to end. Closing the cursor does not end a read from MongoDB in progress on the thread, and a read from a connection that stopped answering does not return: the consumer waits for such a read up to the shutdownAwaitTermination of the ExecutorServiceManager (10 seconds by default), then logs a WARN, interrupts the thread and leaves it behind. A thread that routes an exchange is waited for, and not interrupted, as the graceful shutdown bounds that wait with its own timeout.

Tailable Cursor Consumer

MongoDB offers a mechanism to instantaneously consume ongoing data from a collection, by keeping the cursor open just like the tail -f command of *nix systems. This mechanism is significantly more efficient than a scheduled poll, due to the fact that the server pushes new data to the client as it becomes available, rather than making the client ping back at scheduled intervals to fetch new data. It also reduces otherwise redundant network traffic.

There is only one requisite to use tailable cursors: the collection must be a "capped collection", meaning that it will only hold N objects, and when the limit is reached, MongoDB flushes old objects in the same order they were originally inserted. For more information, please refer to: http://www.mongodb.org/display/DOCS/Tailable+Cursors.

The Camel MongoDB component implements a tailable cursor consumer, making this feature available for you to use in your Camel routes. As new objects are inserted, MongoDB will push them as Document in natural order to your tailable cursor consumer, who will transform them to an Exchange and will trigger your route logic.

How the tailable cursor consumer works

To turn a cursor into a tailable cursor, a few special flags are to be signalled to MongoDB when first generating the cursor. Once created, the cursor will then stay open and will block upon calling the MongoCursor.next() method until new data arrives. However, the MongoDB server reserves itself the right to kill your cursor if new data doesn’t appear after an indeterminate period. If you are interested to continue consuming new data, you have to regenerate the cursor. And to do so, you will have to remember the position where you left off or else you will start consuming from the top again.

The Camel MongoDB tailable cursor consumer takes care of all these tasks for you. You will need to provide the key to some field in your data of increasing nature, which will act as a marker to position your cursor every time it is regenerated, e.g. a timestamp, a sequential ID, etc. It can be of any datatype supported by MongoDB. Date, Strings and Integers are found to work well. We call this mechanism "tail tracking" in the context of this component.

The consumer will remember the last value of this field, and whenever the cursor is to be regenerated, it will run the query with a filter like: increasingField > lastValue, so that only unread data is consumed.

Setting the increasing field: Set the key of the increasing field on the endpoint URI tailTrackIncreasingField option. In Camel 2.10, it must be a top-level field in your data, as nested navigation for this field is not yet supported. That is, the "timestamp" field is okay, but nested.timestamp will not work. Please open a ticket in the Camel JIRA if you do require support for nested increasing fields.

Cursor regeneration delay: One thing to note is that if new data is not already available upon initialisation, MongoDB will kill the cursor instantly. Since we don’t want to overwhelm the server in this case, a cursorRegenerationDelay option has been introduced (with a default value of 1000ms.), which you can modify to suit your needs.

An example:

  • Java

  • XML

  • YAML

from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime")
    .id("tailableCursorConsumer1")
    .autoStartup(false)
    .to("mock:test");
<route id="tailableCursorConsumer1" autoStartup="false">
  <from uri="mongodb:myDb?database=flights&amp;collection=cancellations&amp;tailTrackIncreasingField=departureTime"/>
  <to uri="mock:test"/>
</route>
- route:
    id: tailableCursorConsumer1
    autoStartup: false
    from:
      uri: mongodb:myDb
      parameters:
        database: flights
        collection: cancellations
        tailTrackIncreasingField: departureTime
      steps:
        - to:
            uri: mock:test

The above route will consume from the flights.cancellations capped collection, using departureTime as the increasing field, with a default regeneration cursor delay of 1000ms.

Persistent tail tracking

Standard tail tracking is volatile and the last value is only kept in memory. However, in practice, you will need to restart your Camel container sometimes. However, your last value would then be lost and your tailable cursor consumer would start consuming from the top again, very likely sending duplicate records into your route.

To overcome this situation, you can enable the persistent tail tracking feature to keep track of the last consumed increasing value in a special collection inside your MongoDB database too. When the consumer initialises again, it will restore the last tracked value and continue as if nothing happened.

The last read value is persisted on two occasions: every time the cursor is regenerated and when the consumer shuts down. We may consider persisting at regular intervals too in the future (flush every 5 seconds) for added robustness if the demand is there. To request this feature, please open a ticket in the Camel JIRA.

Enabling persistent tail tracking

To enable this function, set at least the following options on the endpoint URI:

  • persistentTailTracking option to true

  • persistentId option to a unique identifier for this consumer, so that the same collection can be reused across many consumers

Additionally, you can set the tailTrackDb, tailTrackCollection and tailTrackField options to customise where the runtime information will be stored. Refer to the endpoint options table at the top of this page for descriptions of each option.

For example, the following route will consume from the "flights.cancellations" capped collection, using "departureTime" as the increasing field, with a default regeneration cursor delay of 1000ms, with persistent tail tracking turned on, and persisting under the "cancellationsTracker" id on the "flights.camelTailTracking", storing the last processed value under the "lastTrackingValue" field (camelTailTracking and lastTrackingValue are defaults).

  • Java

  • XML

  • YAML

from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime&persistentTailTracking=true" +
     "&persistentId=cancellationsTracker")
    .id("tailableCursorConsumer2")
    .autoStartup(false)
    .to("mock:test");
<route id="tailableCursorConsumer2" autoStartup="false">
  <from uri="mongodb:myDb?database=flights&amp;collection=cancellations&amp;tailTrackIncreasingField=departureTime&amp;persistentTailTracking=true&amp;persistentId=cancellationsTracker"/>
  <to uri="mock:test"/>
</route>
- route:
    id: tailableCursorConsumer2
    autoStartup: false
    from:
      uri: mongodb:myDb
      parameters:
        database: flights
        collection: cancellations
        tailTrackIncreasingField: departureTime
        persistentTailTracking: true
        persistentId: cancellationsTracker
      steps:
        - to:
            uri: mock:test

Below is another example identical to the one above, but where the persistent tail tracking runtime information will be stored under the "trackers.camelTrackers" collection, in the "lastProcessedDepartureTime" field:

  • Java

  • XML

  • YAML

from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime&persistentTailTracking=true" +
     "&persistentId=cancellationsTracker&tailTrackDb=trackers&tailTrackCollection=camelTrackers" +
     "&tailTrackField=lastProcessedDepartureTime")
    .id("tailableCursorConsumer3")
    .autoStartup(false)
    .to("mock:test");
<route id="tailableCursorConsumer3" autoStartup="false">
  <from uri="mongodb:myDb?database=flights&amp;collection=cancellations&amp;tailTrackIncreasingField=departureTime&amp;persistentTailTracking=true&amp;persistentId=cancellationsTracker&amp;tailTrackDb=trackers&amp;tailTrackCollection=camelTrackers&amp;tailTrackField=lastProcessedDepartureTime"/>
  <to uri="mock:test"/>
</route>
- route:
    id: tailableCursorConsumer3
    autoStartup: false
    from:
      uri: mongodb:myDb
      parameters:
        database: flights
        collection: cancellations
        tailTrackIncreasingField: departureTime
        persistentTailTracking: true
        persistentId: cancellationsTracker
        tailTrackDb: trackers
        tailTrackCollection: camelTrackers
        tailTrackField: lastProcessedDepartureTime
      steps:
        - to:
            uri: mock:test

Change Streams Consumer

Change Streams allow applications to access real-time data changes without the complexity and risk of tailing the MongoDB oplog. Applications can use change streams to subscribe to all data changes on a collection and immediately react to them. Because change streams use the aggregation framework, applications can also filter for specific changes or transform the notifications at will. The exchange body will contain the full document of any change.

To configure Change Streams Consumer you need to specify consumerType, database, collection and optional JSON property streamFilter to filter events. That JSON property is standard MongoDB $match aggregation. It could be easily specified using the DSL configuration:

  • Java

  • XML

  • YAML

from("mongodb:myDb?consumerType=changeStreams&database=flights&collection=tickets&streamFilter={ '$match':{'$or':[{'fullDocument.stringValue': 'specificValue'}]} }")
    .to("mock:test");
<route id="filterConsumer">
  <from uri="mongodb:myDb?consumerType=changeStreams&amp;database=flights&amp;collection=tickets&amp;streamFilter={ '$match':{'$or':[{'fullDocument.stringValue': 'specificValue'}]} }"/>
  <to uri="mock:test"/>
</route>
- route:
    id: filterConsumer
    from:
      uri: mongodb:myDb
      parameters:
        consumerType: changeStreams
        database: flights
        collection: tickets
        streamFilter: "{ '$match':{'$or':[{'fullDocument.stringValue': 'specificValue'}]} }"
      steps:
        - to:
            uri: mock:test
You can externalize the streamFilter value into a property placeholder which allows the endpoint URI parameters to be cleaner and easier to read.

Change Streams Resume

The Change Streams consumer supports resume in two complementary ways:

  • Endpoint options (changeStreamTokenRepository, changeStreamToken) to restore and persist the resume token.

  • The Resume Strategies EIP (resumable()) for route-level resume handling.

When a route id is configured, the token key is computed as <routeId>/<collection>. If no route id is configured, Camel falls back to the endpoint URI.

The resume token is a BSON document. It is persisted as a serialized JSON string and parsed back to a BsonDocument when restored.

The following example configures endpoint-level token persistence:

from("mongodb:myDb?consumerType=changeStreams"
   + "&database=flights"
   + "&collection=tickets"
   + "&changeStreamTokenRepository=#changeStreamTokenRepo")
  .id("resumeChangeStreamConsumer")
  .to("mock:test");

The following example configures route-level resume strategy support:

MongoDbResumeStrategyConfigurationBuilder configurationBuilder =
    MongoDbResumeStrategyConfigurationBuilder.newBuilder()
        .withStateRepository(memoryStateRepository)
        .withResumeCache(new CaffeineCache<>(100));

from("mongodb:myDb?consumerType=changeStreams&database=flights&collection=tickets")
  .id("resumeChangeStreamConsumer")
  .resumable().configuration(configurationBuilder)
  .to("mock:test");

You can use only endpoint options, only route-level resumable configuration, or both depending on your deployment requirements.

While no change of the collection arrives, the change stream still reads the oplog, which the other collections of the replica set write. After each getMore that returns no change (MongoDB waits up to one second for a change), the consumer takes the post batch resume token of the change stream: the position up to which it has read the oplog. It stores that token in the changeStreamTokenRepository, so a new change stream resumes after it.

The consumer stores this token only when the exchange of the last change it read completed. A change whose exchange failed is therefore read again by a new change stream, unless a later change completed, as the token of that later change already passes the failed one.

The post batch resume token is not passed to a resume strategy, which only gets the tokens of the exchanges.

If the oplog no longer has the token to resume after (MongoDB answers ChangeStreamHistoryLost), for example because the route was stopped for longer than the oplog window, the consumer logs a WARN and opens the change stream at the current time: the changes made since that token may not have been consumed.

Type conversions

The MongoDbBasicConverters type converter included with the camel-mongodb component provides the following conversions:

Name From type To type How?

fromMapToDocument

Map

Document

constructs a new Document via the new Document(Map m) constructor.

fromDocumentToMap

Document

Map

Document already implements Map.

fromStringToDocument

String

Document

uses com.mongodb.Document.parse(String s).

fromStringToObjectId

String

ObjectId

constructs a new ObjectId via the new ObjectId(s)

fromFileToDocument

File

Document

uses fromInputStreamToDocument under the hood

fromInputStreamToDocument

InputStream

Document

converts the inputstream bytes to a Document

fromStringToList

String

List<Bson>

uses org.bson.codecs.configuration.CodecRegistries to convert to BsonArray then to List<Bson>.

This type converter is auto-discovered, so you don’t need to configure anything manually.

Examples

Example route

The following route defined in Spring XML executes the operation getDbStats on a collection.

Get DB stats for specified collection

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mongodb:mongoBean?database={{mongodb.database}}&collection={{mongodb.collection}}&operation=getDbStats")
    .to("direct:result");
<route>
  <from uri="direct:start" />
  <!-- using bean 'mongoBean' defined above -->
  <to uri="mongodb:mongoBean?database={{mongodb.database}}&amp;collection={{mongodb.collection}}&amp;operation=getDbStats" />
  <to uri="direct:result" />
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mongodb:mongoBean
            parameters:
              database: "{{mongodb.database}}"
              collection: "{{mongodb.collection}}"
              operation: getDbStats
        - to:
            uri: direct:result