Mule ESB create MongoDB 2dsphere Index

Mule ESB 3.5 works like a bliss with MongoDB 2.4.9,  providing an easy way to configure the connection. A template for MongoDB configuration looks like:

<mongo:config doc:name=”MongoDb”
name=”MongoDatabase”
database=”%databaseName%”
username=”%databaseUsername%”
password=”%databasePassword%”
host=”%databaseHost%”
port=”%databasePort%”>

The MongoDB connector provided, gives the user the possibility to easily configure almost any database operation.

But what should be done when the operation we want to perform is not quite straightforward? An example to this is creating a 2dsphere index. Even though, the MongoDB connector provides “Create Index” operation, one can configure just the order of the index, but not its type.

An approach for these situations without the necessity to  write custom code is to use the “Execute command” operation provided. This operation is a representation of db.runCommand.

So, comming back to the 2dsphere index, the creation using db.runCommand would normally look like:

db.runCommand( { eval :function() {db.collectionName.ensureIndex( {geolocation : ‘2dsphere’} ) } } )

In case we want to create the index using Mule the following connector configuration is to be done:

MongoDB mule

or if you prefer XML version, the previous photo is translated into:

<mongo:execute-command config-ref=”MongoDatabase” commandName=”eval” commandValue=”function(){db.collectionName.ensureIndex({geolocation : ‘2dsphere’})}” doc:name=”Mongo DB”/>

The usage of the “Execute command” operation seems to be straightforward, but at the moment this article was written the documentation for mule:execute-command was lacking a proper example.

2 Comments

  1. Reply
    Gaurav Prajapati February 18, 2016

    Hello Andra,
    I want to get distinct values from MopngoDB’s collection.
    I am trying this query in mongodb
    db.runCommand ( { distinct: “myCollection”, key: “name” } ).
    Now how to execute this command using MuleSoft.
    My mule flow

    I am using Mule community edition 3.7.0 and MongoDB version 3.2.

Leave a Reply

Your email address will not be published. Required fields are marked *