camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Camel > MongoDB
Date Fri, 17 Feb 2012 14:37:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2042/9/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/MongoDB">MongoDB</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~raulvk">Raul
Kripalani</a>
    </h4>
        <br/>
                         <h4>Changes (5)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" > <br>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}}. <br></td></tr>
            <tr><td class="diff-changed-lines" >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 <span class="diff-added-words"style="background-color: #dfd;">(single or multiple
insert)</span> depending on the input. <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">Example:
<br> <br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br>from(&quot;direct:insert&quot;)
<br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >h4. save <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >The save operation is equivalent
to an upsert (UPdate, inSERT) operation, where the record will be inserted if it doesn&#39;t
exist, or else it will be updated. <span class="diff-added-words"style="background-color:
#dfd;">MongoDB will perform the matching based on the _id field.</span> <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">MongoDB
will perform the matching based on the _id field. <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">Beware
that in case of an update, the object will be replaced entirely and the usage of [MongoDB&#39;s
$modifiers|http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations] is not
permitted. Therefore, if you want to manipulate the object if it already exists, you have
two options: <br># 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. <br># use
the update operation with [$modifiers|http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations],
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. <br> <br>For example: <br> <br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br>from(&quot;direct:insert&quot;)
<br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="MongoDB-CamelMongoDBcomponent"></a>Camel MongoDB component</h2>

<p><b>Available as of Camel 2.10</b></p>

<p>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.</p>

<p>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.</p>

<p>MongoDB is a very popular NoSQL solution and 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).</p>

<p>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 <a href="http://www.mongodb.org/" class="external-link"
rel="nofollow">http://www.mongodb.org/</a>.</p>

<h2><a name="MongoDB-URIformat"></a>URI format</h2>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
mongodb:connectionBean?database=databaseName&amp;collection=collectionName&amp;operation=operationName[&amp;moreOptions...]
</pre>
</div></div>

<h2><a name="MongoDB-Endpointoptions"></a>Endpoint options</h2>

<p>MongoDB endpoints support the following options, depending on whether they are acting
like a Producer or as a Consumer (options vary based on the consumer type too).</p>

<div class="confluenceTableSmall"></div>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Default Value </th>
<th class='confluenceTh'> Description </th>
<th class='confluenceTh'> Producer </th>
<th class='confluenceTh'> Tailable Cursor Consumer </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>database</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> <b>Required.</b> 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&nbsp;<tt>CamelMongoDbDatabase</tt> header is
set. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>collection</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> <b>Required.</b> The name of the collection (within
the specified database) to which this endpoint will be bound.&nbsp;All operations will
be executed against this database unless dynamicity is enabled and the&nbsp;<tt>CamelMongoDbDatabase</tt>
header is set. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>operation</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> <b>Required for producers.</b> The id of the operation
this endpoint will execute. Pick from the following:
<ul>
	<li>Query operations: <tt>findById</tt>, <tt>findOneByQuery</tt>,
<tt>findAll</tt>, <tt>count</tt></li>
	<li>Write operations: <tt>insert</tt>, <tt>save</tt>, <tt>update</tt></li>
	<li>Delete operations: <tt>remove</tt></li>
	<li>Other operations: <tt>getDbStats</tt>, <tt>getColStats</tt></li>
</ul>
</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>createCollection</tt> </td>
<td class='confluenceTd'> true </td>
<td class='confluenceTd'> 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 <tt>false</tt> and the collection doesn't exist, an initialisation exception
will be thrown. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>invokeGetLastError</tt> </td>
<td class='confluenceTd'> false (behaviour may be inherited from connections WriteConcern)
</td>
<td class='confluenceTd'> Instructs the MongoDB Java driver to invoke <tt>getLastError()</tt>
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 <tt>getLastError()</tt>
on the <tt>WriteResult</tt> object returned or by setting the appropriate <tt>WriteConcern</tt>.
If the backend operation has not finished yet, the client will block until the result is available.
Setting this option to <tt>true</tt> will make the endpoint behave synchronously
and return an Exception if the underlying operation failed. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>writeConcern</tt> </td>
<td class='confluenceTd'> none (driver's default) </td>
<td class='confluenceTd'> Set a <tt>WriteConcern</tt> on the operation out
of MongoDB's parameterised values. See <a href="http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html#valueOf(java.lang.String)"
class="external-link" rel="nofollow">WriteConcern.valueOf(String)</a>. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>writeConcernRef</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> Sets a custom <tt>WriteConcern</tt> that exists
in the Registry. Specify the bean name. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>readPreference</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> Sets a <tt>ReadPreference</tt> on the connection.
Accepted values: the name of any inner subclass of <a href="http://api.mongodb.org/java/current/com/mongodb/ReadPreference.html"
class="external-link" rel="nofollow">ReadPreference</a>. For example: <tt>PrimaryReadPreference</tt>,
<tt>SecondaryReadPreference</tt>, <tt>TaggedReadPreference</tt>. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>dynamicity</tt> </td>
<td class='confluenceTd'> false </td>
<td class='confluenceTd'> If set to true, the endpoint will inspect the <tt>CamelMongoDbDatabase</tt>
and <tt>CamelMongoDbCollection</tt> 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. </td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
<td class='confluenceTd'>&nbsp;</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>persistentTailTracking</tt> </td>
<td class='confluenceTd'> false </td>
<td class='confluenceTd'> Enables or disables persistent tail tracking for Tailable
Cursor consumers. See below for more information. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>persistentId</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> <b>Required if persistent tail tracking is enabled.</b>
The id of this persistent tail tracker, to separate its records from the rest on the tail-tracking
collection. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>tailTrackingIncreasingField</tt> </td>
<td class='confluenceTd'> none </td>
<td class='confluenceTd'> <b>Required if persistent tail tracking is enabled.</b>
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 &gt; 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. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>cursorRegenerationDelay</tt> </td>
<td class='confluenceTd'> 1000ms </td>
<td class='confluenceTd'> Establishes how long the endpoint will wait to regenerate
the cursor after it has been killed by the MongoDB server (normal behaviour). </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>tailTrackDb</tt> </td>
<td class='confluenceTd'> same as endpoint's </td>
<td class='confluenceTd'> Database on which the persistent tail tracker will store its
runtime information. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>tailTrackCollection</tt> </td>
<td class='confluenceTd'> camelTailTracking </td>
<td class='confluenceTd'> Collection on which the persistent tail tracker will store
its runtime information. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>tailTrackField</tt> </td>
<td class='confluenceTd'> lastTrackingValue </td>
<td class='confluenceTd'> Field in which the persistent tail tracker will store the
last tracked value. </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <img class="emoticon" src="/confluence/images/icons/emoticons/check.gif"
height="16" width="16" align="absmiddle" alt="" border="0"/> </td>
</tr>
</tbody></table>
</div>


<h2><a name="MongoDB-MongoDBoperationsproducerendpoints"></a>MongoDB operations
- producer endpoints</h2>

<h3><a name="MongoDB-Queryoperations"></a>Query operations</h3>

<h4><a name="MongoDB-findById"></a>findById</h4>

<p>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 <a href="http://bsonspec.org/#/specification" class="external-link"
rel="nofollow">http://bsonspec.org/#/specification</a> and <a href="http://www.mongodb.org/display/DOCS/Java+Types"
class="external-link" rel="nofollow">http://www.mongodb.org/display/DOCS/Java+Types</a>.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"direct:findById"</span>)
    .to(<span class="code-quote">"mongodb:myDb?database=flights&amp;collection=tickets&amp;operation&amp;operation=findById"</span>)
    .to(<span class="code-quote">"mock:resultFindById"</span>);
</pre>
</div></div>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>Supports fields filter</b><br
/>This operation supports specifying a fields filter. See <a href="/confluence/pages/createpage.action?spaceKey=CAMEL&amp;title=Specifying+a+fields+filter&amp;linkCreation=true&amp;fromPageId=27838322"
class="createlink">Specifying a fields filter#FieldsFilter</a>.</td></tr></table></div>

<h4><a name="MongoDB-findOneByQuery"></a>findOneByQuery</h4>

<p>Use this operation to retrieve just one element from the collection that matches
a MongoDB query. The query object is extracted from the IN message body, i.e. it should be
of type <tt>DBObject</tt> or convertible to <tt>DBObject</tt>. See
<a href="/confluence/pages/createpage.action?spaceKey=CAMEL&amp;title=Type+conversions&amp;linkCreation=true&amp;fromPageId=27838322"
class="createlink">Type conversions</a>.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"direct:findOneByQuery"</span>)
    .to(<span class="code-quote">"mongodb:myDb?database=flights&amp;collection=tickets&amp;operation&amp;operation=findOneByQuery"</span>)
    .to(<span class="code-quote">"mock:resultFindOneByQuery"</span>);
</pre>
</div></div>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>Supports fields filter</b><br
/>This operation supports specifying a fields filter. See <a href="/confluence/pages/createpage.action?spaceKey=CAMEL&amp;title=Specifying+a+fields+filter&amp;linkCreation=true&amp;fromPageId=27838322"
class="createlink">Specifying a fields filter#FieldsFilter</a>.</td></tr></table></div>

<h4><a name="MongoDB-findAll"></a>findAll</h4>

<p>The <tt>findAll</tt> operation returns all documents matching a query,
or none at all, in which case all documents contained in the collection are returned.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"direct:findAll"</span>)
    .to(<span class="code-quote">"mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=findAll"</span>)
    .to(<span class="code-quote">"mock:resultFindAll"</span>);
</pre>
</div></div>

<p>Paging and efficient retrieval is supported via the following headers:</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Header key </th>
<th class='confluenceTh'> Quick constant </th>
<th class='confluenceTh'> Description (extracted from MongoDB API doc) </th>
<th class='confluenceTh'> Expected type </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelMongoDbNumToSkip</tt> </td>
<td class='confluenceTd'> <tt>MongoDbConstants.NUM_TO_SKIP</tt> </td>
<td class='confluenceTd'> Discards a given number of elements at the beginning of the
cursor. </td>
<td class='confluenceTd'> int/Integer </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelMongoDbLimit</tt> </td>
<td class='confluenceTd'> <tt>MongoDbConstants.LIMIT</tt> </td>
<td class='confluenceTd'> Limits the number of elements returned. </td>
<td class='confluenceTd'> int/Integer </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelMongoDbBatchSize</tt> </td>
<td class='confluenceTd'> <tt>MongoDbConstants.BATCH_SIZE</tt> </td>
<td class='confluenceTd'> Limits the number of elements returned in one batch. A cursor
typically fetches a batch of result objects and store them locally. If batchSize is positive,
it represents the size of each batch of objects retrieved. It can be adjusted to optimize
performance and limit data transfer. If batchSize is negative, it will limit of number objects
returned, that fit within the max batch size limit (usually 4MB), and cursor will be closed.
For example if batchSize is -10, then the server will return a maximum of 10 documents and
as many as can fit in 4MB, then close the cursor. Note that this feature is different from
limit() in that documents must fit within a maximum size, and it removes the need to send
a request to close the cursor server-side. The batch size can be changed even after a cursor
is iterated, in which case the setting will apply on the next batch retrieval.</td>
<td class='confluenceTd'> int/Integer </td>
</tr>
</tbody></table>
</div>


<p>Additionally, you can set a sortBy criteria by putting the relevant <tt>DBObject</tt>
describing your sorting in the <tt>CamelMongoDbSortBy</tt> header, quick constant:
<tt>MongoDbConstants.SORT_BY</tt>.</p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>Supports fields filter</b><br
/>This operation supports specifying a fields filter. See <a href="/confluence/pages/createpage.action?spaceKey=CAMEL&amp;title=Specifying+a+fields+filter&amp;linkCreation=true&amp;fromPageId=27838322"
class="createlink">Specifying a fields filter#FieldsFilter</a>.</td></tr></table></div>

<p><a name="MongoDB-FieldsFilter"></a></p>
<h4><a name="MongoDB-Specifyingafieldfilter"></a>Specifying a field filter</h4>

<p>Query operations will, by default, return matching objects in their entirety. If
your documents are large and you are only interested in retrieving a subset of their fields,
you can specify a field filter in all query operations, simply by setting the relevant <tt>DBObject</tt>
(or type convertible to <tt>DBObject</tt>, such as a JSON String, Map, etc.) on
the <tt>CamelMongoDbFieldsFilter</tt> header, constant shortcut: <tt>MongoDbConstants.FIELDS_FILTER</tt>.
</p>

<p>An example that uses MongoDB's BasicDBObjectBuilder to simplify the creation of DBObjects:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
DBObject fieldFilter = BasicDBObjectBuilder.start().add(<span class="code-quote">"_id"</span>,
0).add(<span class="code-quote">"fixedField"</span>, 0).get();
<span class="code-object">Object</span> result = template.requestBodyAndHeader(<span
class="code-quote">"direct:findAll"</span>, (<span class="code-object">Object</span>)
<span class="code-keyword">null</span>, MongoDbConstants.FIELDS_FILTER, fieldFilter);
</pre>
</div></div>

<h3><a name="MongoDB-Create%2Fupdateoperations"></a>Create/update operations</h3>

<h4><a name="MongoDB-insert"></a>insert</h4>

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

<p>Example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"direct:insert"</span>)
    .to(<span class="code-quote">"mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=insert"</span>);
</pre>
</div></div>

<p>The operation will return a WriteResult, and depending on the WriteConcern or the
value of the <tt>invokeGetLastError</tt> option, the getLastError would have been
called already or not. If you want to access the ultimate result of the write operation, you
need to retrieve the <tt>CommandResult</tt> by calling <tt>getLastError()</tt>
or <tt>getCachedLastError()</tt> on the <tt>WriteResult</tt>. Then
you can verify the result by calling <tt>CommandResult.ok()</tt>, <tt>CommandResult.getErrorMessage()</tt>
and/or <tt>CommandResult.getException()</tt>.</p>

<p>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 (and for Camel to notice, you will need to enable
invokeGetLastError or set a WriteConcern that waits for the write result). 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).</p>

<h4><a name="MongoDB-save"></a>save</h4>

<p>The save operation is equivalent to an upsert (UPdate, inSERT) operation, where the
record will be inserted if it doesn't exist, or else it will be updated. MongoDB will perform
the matching based on the _id field.</p>

<p>Beware that in case of an update, the object will be replaced entirely and the usage
of <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations" class="external-link"
rel="nofollow">MongoDB's $modifiers</a> is not permitted. Therefore, if you want
to manipulate the object if it already exists, you have two options:</p>
<ol>
	<li>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.</li>
	<li>use the update operation with <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations"
class="external-link" rel="nofollow">$modifiers</a>, 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.</li>
</ol>


<p>For example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"direct:insert"</span>)
    .to(<span class="code-quote">"mongodb:myDb?database=flights&amp;collection=tickets&amp;operation=save"</span>);
</pre>
</div></div>

<h4><a name="MongoDB-update"></a>update</h4>

<p>Update one or multiple records on the collection. Requires a List&lt;DBObject&gt;
as the IN message body containing exactly 2 elements:</p>
<ul>
	<li>Element 1 (index 0) =&gt; filter query =&gt; determines what objects will
be affected, same as a typical query object</li>
	<li>Element 2 (index 1) =&gt; update rules =&gt; how matched objects will be
updated. All <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations"
class="external-link" rel="nofollow">modifier operations</a> from MongoDB are supported.</li>
</ul>


<div class='panelMacro'><table class='noteMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/warning.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>Multiupdates</b><br
/>By default, MongoDB will only update 1 object even if multiple objects match the filter
query. To instruct MongoDB to update <b>all</b> matching records, set the <tt>CamelMongoDbMultiUpdate</tt>
IN message header to <tt>true</tt>.</td></tr></table></div>

<p>Supports the following IN message headers:</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Header key </th>
<th class='confluenceTh'> Quick constant </th>
<th class='confluenceTh'> Description (extracted from MongoDB API doc) </th>
<th class='confluenceTh'> Expected type </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelMongoDbMultiUpdate</tt> </td>
<td class='confluenceTd'> <tt>MongoDbConstants.MULTIUPDATE</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> boolean/Boolean </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelMongoDbUpsert</tt> </td>
<td class='confluenceTd'> <tt>MongoDbConstants.UPSERT</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> boolean/Boolean </td>
</tr>
</tbody></table>
</div>


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

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// route: from(<span class="code-quote">"direct:update"</span>).to(<span
class="code-quote">"mongodb:myDb?database=science&amp;collection=notableScientists&amp;operation=update"</span>);
</span>DBObject filterField = <span class="code-keyword">new</span> BasicDBObject(<span
class="code-quote">"filterField"</span>, <span class="code-keyword">true</span>);
DBObject updateObj = <span class="code-keyword">new</span> BasicDBObject(<span
class="code-quote">"$set"</span>, <span class="code-keyword">new</span>
BasicDBObject(<span class="code-quote">"scientist"</span>, <span class="code-quote">"Darwin"</span>));
<span class="code-object">Object</span> result = template.requestBodyAndHeader(<span
class="code-quote">"direct:update"</span>, <span class="code-keyword">new</span>
<span class="code-object">Object</span>[] {filterField, updateObj}, MongoDbConstants.MULTIUPDATE,
<span class="code-keyword">true</span>);
</pre>
</div></div>

<h3><a name="MongoDB-Deleteoperations"></a>Delete operations</h3>


<h4><a name="MongoDB-remove"></a>remove</h4>


<h3><a name="MongoDB-Otheroperations"></a>Other operations</h3>

<h4><a name="MongoDB-count"></a>count</h4>

<h4><a name="MongoDB-getDbStats"></a>getDbStats</h4>

<h4><a name="MongoDB-getColStats"></a>getColStats</h4>

<h3><a name="MongoDB-Dynamicoperations"></a>Dynamic operations</h3>

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

<p>For example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-object">Object</span> result = template.requestBodyAndHeader(<span
class="code-quote">"direct:insert"</span>, <span class="code-quote">"irrelevantBody"</span>,
MongoDbConstants.OPERATION_HEADER, <span class="code-quote">"count"</span>);
assertTrue(<span class="code-quote">"Result is not of type <span class="code-object">Long</span>"</span>,
result <span class="code-keyword">instanceof</span> <span class="code-object">Long</span>);
</pre>
</div></div>

<h2><a name="MongoDB-Typeconversions"></a>Type conversions</h2>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/MongoDB">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=27838322&revisedVersion=12&originalVersion=11">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/MongoDB?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message