Skip to content

MongoDB connector example

The MongoDB Connector can be used to perform CRUD operations in the local database as well as in MongoDB Atlas (cloud version of MongoDB).

What you'll build

This example explains how to use MongoDB Connector to insert and find documents from a MongoDB database.

The sample API given below demonstrates how the MongoDB connector can be used to connect to the MongoDB Server and perform insert many and find operations on it.

  • /insertmany: The user sends a request payload that includes the connection information, collection name, and the documents to be inserted. This request is sent to the integration runtime by invoking the MongodbConnector API. This will insert the documents into the MongoDB database.

    Insert many function

  • /find: The user sends the request payload containing the connection information, collection name, and the find query. This request is sent to the integration runtime by invoking the MongodbConnector API. Once the API is invoked, it returns the documents matching the find query.

    Find function

If you do not want to configure this yourself, you can simply get the project and run it.

Before you begin

If you want to connect to MongoDB Atlas, follow the steps mentioned below to get the connection string.

  1. In the Clusters view, click Connect for the cluster to which you want to connect.

  2. Click Choose a connection method.

  3. Click Connect your application.

  4. Select Java from the Driver menu.

  5. Select the correct driver version from the Version(3.3) menu.

  6. Clear the Include full driver code example check box to get the connection string.

Create the integration project

  1. Create a new integration project named MongodbConnector.

    Create project

  2. Click + on Extension panal APIs to create the REST API.

    Adding a Rest API

  3. Provide the API name as MongoConnector and the API context as /mongodbconnector. Click create. Adding Rest API Values

  4. Delete default resource created by Extension. Delete default resource
    Then click + Resource to create the /insertmany resource. This API resource inserts documents into the MongoDB database. Let's use a URL_template as URL style and insert /insertmany to URI Template. Select methods as Post. Then click create. Adding the API resource.
    Click created /insertmany resource open Resource View. Then click + arrow below Start node to open side panel. Open Resource View

  5. Select Connectors and search mongodb connector. Click the mongodb connector to open opareation panal then click insertMany. Adding the insert many operation.

  6. Create a connection by clicking Add new Connection.

    Following values can be provided when connecting to the MongoDB database.

    • Connection Type - URI
    • Connection Name - connectionURI
    • Connection URI - mongodb+srv://server.example.com/?connectTimeoutMS=300000&authSource=aDifferentAuthDB
    • Database - TestDatabase

    Adding the connection.

  7. After the connection is successfully created, you can select the new connection from the 'Connection' menu in the properties view.

    Selecting the connection.

  8. Next, provide JSON expressions for the following two properties. These expressions will retrieve the respective values from the JSON request payload.

    • Collection - json-eval($.collection)
    • Documents - json-eval($.documents)
  9. Click + arrow under insertMany node then click Respond Mediator and submit to add to the canvas. This returns the response message to the client (after inserting documents) as shown below.

    Adding the respond mediator.
    Final diagram should look like this. Final Diagram

  10. Create the next API resource (which is /find) by doing same steps as create /insertmany. This API resource will find all the documents matching the find query given by the user. This will also be a POST request.

  11. Select 'connectionURI' as the connection from the 'Connection' menu in the properties view.

  12. Next, provide JSON expressions for the following two properties. These expressions will retrieve the respective values from the JSON request payload.

    • Collection - json-eval($.collection)
    • Query - json-eval($.query)
  13. Add Respond Mediator to the canvas. This returns the response message to the client (after retrieving documents) as shown below.

  14. You can find the complete API XML configuration below. Now you can switch to the Source view and check the XML configuration files of the created API and sequences.

<?xml version="1.0" encoding="UTF-8"?>
<api context="/mongodbconnector" name="MongoConnector" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="POST" uri-template="/insertmany">
        <inSequence>
            <property expression="json-eval($.collection)" name="collection" scope="default" type="JSON"/>
            <property expression="json-eval($.documents)" name="documents" scope="default" type="JSON"/>
            <mongodb.insertMany configKey="connectionURI">
                <collection>{$ctx:collection}</collection>
                <documents>{$ctx:documents}</documents>
                <ordered>True</ordered>
            </mongodb.insertMany>
            <respond/>
        </inSequence>
        <faultSequence>
        </faultSequence>
    </resource>
    <resource methods="POST" uri-template="/find">
        <inSequence>
            <property expression="json-eval($.collection)" name="collection" scope="default" type="JSON"/>
            <property expression="json-eval($.query)" name="query" scope="default" type="JSON"/>
            <mongodb.find configKey="connectionURI">
                <collection>{$ctx:collection}</collection>
                <query>{$ctx:query}</query>
            </mongodb.find>
            <respond/>
        </inSequence>
        <faultSequence>
        </faultSequence>
    </resource>
</api>

Get the project

You can download the ZIP file and extract the contents to get the project code.

Download ZIP

Deployment

To deploy and run the project, refer to the Build and Run guide.

You can further refer the application deployed through the CLI tool. See the instructions on managing integrations from the CLI.

Testing

Insert Many Operation

  1. Create a file named insertmany.json with the following payload:

    {
        "collection": "TestCollection",
        "documents": [
            {
                "name": "Jane Doe",
                "_id": "123"
            },
            {
                "name": "John Doe",
                "_id": "1234"
            },
            {
                "name": "Jane Doe",
                "_id": "12345"
            }
        ]
    }
    
  2. Invoke the API as shown below using the curl command.

    Info

    The Curl application can be downloaded from here.

    curl -H "Content-Type: application/json" --request POST --data @insertmany.json http://localhost:8290/mongodbconnector/insertmany
    

    Expected Response : You should get a response as given below and the data will be added to the database.

    {
        "InsertManyResult": "Successful"
    }
    

Find Operation

Note

In order to find documents by ObjectId, the find query payload should be in the following format:

{
    "query": {
        "_id": {
            "$oid": "6011b180007ce60ab2ad74a5"
        }
    }
}
  1. Create a file called find.json with the following payload.

    {
        "collection": "TestCollection",
        "query": {
            "name": "Jane Doe"
        }
    }
    
  2. Invoke the API using the curl command shown below.

    Info

    Curl Application can be downloaded from here.

    curl -H "Content-Type: application/json" --request POST --data @find.json http://localhost:8290/mongodbconnector/find
    

    Expected Response : You should get a response similar to the one given below.

    [
        {
            "_id": "123",
            "name": "Jane Doe"
        },
        {
            "_id": "12345",
            "name": "Jane Doe"
        }
    ]
    

What's next