Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

Code Block
xml
xml

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

URI format

Code Block

mongodb:connectionBean?database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]

...

Name

Default Value

Description

Producer

Tailable Cursor Consumer

database

none

Required. The name of the database to which this endpoint will be bound. All operations will be executed against this database unless dynamicity is enabled and the CamelMongoDbDatabase header is set.

(tick)

(tick)

collection

none

Required. The name of the collection (within the specified database) to which this endpoint will be bound. All operations will be executed against this database unless dynamicity is enabled and the CamelMongoDbDatabase header is set.

(tick)

(tick)

collectionIndex

none

Camel 2.12: An optional single field index or compound index to create when inserting new collections.

(tick)

 

operation

none

Required for producers. The id of the operation this endpoint will execute. Pick from the following:

  • Query operations: findById, findOneByQuery, findAll, count
  • Write operations: insert, save, update
  • Delete operations: remove
  • Other operations: getDbStats, getColStats, aggregate

(tick)

 

createCollection

true

Determines whether the collection will be automatically created in the MongoDB database during endpoint initialisation if it doesn't exist already. If this option is false and the collection doesn't exist, an initialisation exception will be thrown.

(tick)

 

invokeGetLastError

false (behaviour may be inherited from connections WriteConcern)

Instructs the MongoDB Java driver to invoke getLastError() after every call. Default behaviour in version 2.7.2 of the MongoDB Java driver is that only network errors will cause the operation to fail, because the actual operation is executed asynchronously in the MongoDB server without holding up the client - to increase performance. The client can obtain the real result of the operation by explicitly invoking getLastError() on the WriteResult object returned or by setting the appropriate WriteConcern. If the backend operation has not finished yet, the client will block until the result is available. Setting this option to true will make the endpoint behave synchronously and return an Exception if the underlying operation failed.

(tick)

 

writeConcern

none (driver's default)

Set a WriteConcern on the operation out of MongoDB's parameterised values. See WriteConcern.valueOf(String).

(tick)

 

writeConcernRef

none

Sets a custom WriteConcern that exists in the Registry. Specify the bean name.

(tick)

 

readPreference

none

Available as of Camel 2.12.4, 2.13.1 and 2.14.0: Sets a ReadPreference on the connection. Accepted values : the name of any inner subclass of ReadPreference. For example: PrimaryReadPreference, SecondaryReadPreference, TaggedReadPreferenceare those supported by the ReadPreference#valueOf() public API. Currently as of MongoDB-Java-Driver version 2.12.0 the supported values are: primary, primaryPrefered, secondary, secondaryPrefered and nearest. See also the documentation for more details about this option.

(tick)

 

dynamicity

false

If set to true, the endpoint will inspect the CamelMongoDbDatabase and CamelMongoDbCollection headers of the incoming message, and if any of them exists, the target collection and/or database will be overridden for that particular operation. Set to false by default to avoid triggering the lookup on every Exchange if the feature is not desired.

(tick)

 

writeResultAsHeader

false

Available as of Camel 2.10.3 and 2.11: In write operations (save, update, insert, etc.), instead of replacing the body with the WriteResult object returned by MongoDB, keep the input body untouched and place the WriteResult in the CamelMongoWriteResult header (constant MongoDbConstants.WRITERESULT).

(tick)

 

persistentTailTracking

false

Enables or disables persistent tail tracking for Tailable Cursor consumers. See below for more information.

 

(tick)

persistentId

none

Required if persistent tail tracking is enabled. The id of this persistent tail tracker, to separate its records from the rest on the tail-tracking collection.

 

(tick)

tailTrackingIncreasingField

none

Required if persistent tail tracking is enabled. Correlation field in the incoming record which is of increasing nature and will be used to position the tailing cursor every time it is generated. The cursor will be (re)created with a query of type: tailTrackIncreasingField > lastValue (where lastValue is possibly recovered from persistent tail tracking). Can be of type Integer, Date, String, etc. NOTE: No support for dot notation at the current time, so the field should be at the top level of the document.

 

(tick)

cursorRegenerationDelay

1000ms

Establishes how long the endpoint will wait to regenerate the cursor after it has been killed by the MongoDB server (normal behaviour).

 

(tick)

tailTrackDb

same as endpoint's

Database on which the persistent tail tracker will store its runtime information.

 

(tick)

tailTrackCollection

camelTailTracking

Collection on which the persistent tail tracker will store its runtime information.

 

(tick)

tailTrackField

lastTrackingValue

Field in which the persistent tail tracker will store the last tracked value.

 

(tick)

...

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/#/specification and http://www.mongodb.org/display/DOCS/Java+Types.

Code Block

from("direct:findById")
    .to("mongodb:myDb?database=flights&collection=tickets&operation&operation=findById")
    .to("mock:resultFindById");

...

Example with no query (returns any object of the collection):

Code Block

from("direct:findOneByQuery")
    .to("mongodb:myDb?database=flights&collection=tickets&operation&operation=findOneByQuery")
    .to("mock:resultFindOneByQuery");

Example with a query (returns one matching result):

Code Block

from("direct:findOneByQuery")
    .setBody().constant("{ \"name\": \"Raul Kripalani\" }")
    .to("mongodb:myDb?database=flights&collection=tickets&operation&operation=findOneByQuery")
    .to("mock:resultFindOneByQuery");

...

Example with no query (returns all object in the collection):

Code Block

from("direct:findAll")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
    .to("mock:resultFindAll");

Example with a query (returns all matching results):

Code Block

from("direct:findAll")
    .setBody().constant("{ \"name\": \"Raul Kripalani\" }")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
    .to("mock:resultFindAll");

...

Here is an example that uses MongoDB's BasicDBObjectBuilder to simplify the creation of DBObjects. It retrieves all fields except _id and boringField:

Code Block

// route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll")
DBObject fieldFilter = BasicDBObjectBuilder.start().add("_id", 0).add("boringField", 0).get();
Object result = template.requestBodyAndHeader("direct:findAll", (Object) null, MongoDbConstants.FIELDS_FILTER, fieldFilter);

...

Inserts an new object into the MongoDB collection, taken from the IN message body. Type conversion is attempted to turn it into DBObject 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 - DBObject. All objects are inserted at once. The endpoint will intelligently decide which backend operation to invoke (single or multiple insert) depending on the input.

Example:

Code Block

from("direct:insert")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=insert");

...

  1. perform 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. use 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.

For example:

Code Block

from("direct:insert")
    .to("mongodb:myDb?database=flights&collection=tickets&operation=save");

...

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

Code Block

// route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update");
DBObject filterField = new BasicDBObject("filterField", true);
DBObject updateObj = new BasicDBObject("$set", new BasicDBObject("scientist", "Darwin"));
Object result = template.requestBodyAndHeader("direct:update", new Object[] {filterField, updateObj}, MongoDbConstants.MULTIUPDATE, true);

...

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:

Code Block

// route: from("direct:remove").to("mongodb:myDb?database=science&collection=notableScientists&operation=remove");
DBObject conditionField = new BasicDBObject("conditionField", true);
Object result = template.requestBody("direct:remove", conditionField);

...

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.

Code Block

// from("direct:count").to("mongodb:myDb?database=tickets&collection=flights&operation=count&dynamicity=true");
Long result = template.requestBodyAndHeader("direct:count", "irrelevantBody", MongoDbConstants.COLLECTION, "dynamicCollectionName");
assertTrue("Result is not of type Long", result instanceof Long);

...

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

Code Block

> 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:

Code Block

// 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 DBObject", result instanceof DBObject);

...

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

Code Block

> 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:

Code Block

// 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 DBObject", result instanceof DBObject);

...

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

For example:

Code Block

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

...

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:

Code Block

from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime")
    .id("tailableCursorConsumer1")
    .autoStartup(false)
    .to("mock:test");

...

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).

Code Block

from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime&persistentTailTracking=true" + 
     "&persistentId=cancellationsTracker")
	.id("tailableCursorConsumer2")
	.autoStartup(false)
	.to("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:

Code Block

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");

...