Salesforce MongoDB integration
A simple one way integration between Salesforce and MongoDB can be accomplished using the REST API included in the mongod process. For a more complex and two-way integration one needs to rely on external REST Interface such as Sleepy.Mongoose since the default one provided by MongoDB doesn't support insert, update and delete operations. The default MongoDB REST API is generally used for administrative tasks such as monitoring and alert scripts.
In this article we will see one such simple integration. Based upon the information that you are looking to fetch from your mongo instance you need to first form the REST URL. Refer this link for more details. Once the URL is formed it is just a matter of calling the URL and parsing the JSON response as we saw in our previous article on Salesforce-Jira integration.
Step:1 Remote Site Settings
As we know that Salesforce doesn't allow connecting to any random external systems and requires a prior configuration listing the URL that can be trusted for a connection; here too we need to configure one under Remote Site Settings.
Few points to take a note of here. Notice the URL http://hiccupcard.com and the port number 28017. The REST API is disabled by default, as it could provide unauthenticated access to your data and one has to use --rest on the command line while running mongod instance (i.e mongod --rest
) to enable it, but be aware of security implications. Once enabled the required information can be fetched using the server URL (hiccupcard.com - where the mongod instance is hosted) and port 28017. Also, make sure you open the firewall for port 28017 on the server.
Below are few such URLs from the docs:
-
To get the contents of a collection (note the trailing slash):
http://<domain name>:28017/databaseName/collectionName/
-
Same as db.$cmd.findOne({listDatabase:1}) on the admin database in the shell:
http://<domain name>:28017/admin/$cmd/?filter_listDatabases=1&limit=1
Step:2 Controller
In the below controller we are using the later URL mentioned above to fetch the list of databases in the mongo instance. Following is the JSON response that is send by the rest enabled mongod process which is then parsed and saved in the list mongodbs
. The JSON response is converted to APEX class (Mongoinfo) with the help of Json2Apex
MongodbIntegration
public class MongodbIntegration{
public List<Databases> mongodbs{get;set;}
public class Mongoinfo {
public Integer offset;
public List<Rows> rows;
public Integer total_rows;
public Query query;
public Integer millis;
}
public class Databases {
public String name{get;}
public Integer sizeOnDisk{get;}
public Boolean empty{get;}
}
public class Query {
public Integer listDatabases;
}
public class Rows {
public List<Databases> databases;
public Integer totalSize;
public Integer ok;
}
public MongodbIntegration(){
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('');
req.setMethod('GET');
HttpResponse res = http.send(req);
String JSONContent = res.getBody();
System.debug('Response:'+JSONContent);
mongodbs = new List<Databases>();
JSONParser parser = JSON.createParser(JSONContent);
while (parser.nextToken() != null)
{
if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
Mongoinfo info = (Mongoinfo)parser.readValueAs(Mongoinfo.class);
mongodbs = info.rows[0].databases;
}
}
}
}
JSON Response
{
"offset" : 0,
"rows": [
{ "databases" : [
{ "name" : "hiccupcard",
"sizeOnDisk" : 83886080,
"empty" : false
},
{ "name" : "local",
"sizeOnDisk" : 83886080,
"empty" : false
} ],
"totalSize" : 167772160, "ok" : 1 }
],
"total_rows" : 1 ,
"query" : { "listDatabases" : 1 } ,
"millis" : 1
}
Step:3 Visualforce Page
Below is the simple VF page designed to show the mongodbs
list in neat table form and following is the code for the same.
Mongodb Integration
<apex:page controller="MongodbIntegration" showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">
<html xmlns="" xmlns:xlink="">
<head>
<title>Salesforce Lightning Design System Trailhead Module</title>
<apex:stylesheet value="{!URLFOR($Resource.SLDS090, 'assets/styles/salesforce-lightning-design-system-vf.css')}" />
</head>
<apex:remoteObjects >
<apex:remoteObjectModel name="Account" fields="Id,Name,LastModifiedDate"/>
</apex:remoteObjects>
<body>
REQUIRED SLDS WRAPPER -->
<div class="slds">
<!-- MASTHEAD -->
<p class="slds-text-heading--label slds-m-bottom--small">Salesforce-MongoDB Integration Demo. UI desinged using Salesforce Lightning Design System</p>
<!-- / MASTHEAD -->
<!-- PAGE HEADER -->
<div class="slds-page-header" role="banner">
<!-- LAYOUT GRID -->
<div class="slds-grid">
<!-- GRID COL -->
<div class="slds-col">
<!-- HEADING AREA -->
<!-- MEDIA OBJECT = FIGURE + BODY -->
<div class="slds-media">
<div class="slds-media__figure">
<span class="slds-avatar slds-avatar--large">
<img src="{!URLFOR($Resource.SLDS090, 'assets/images/avatar1.jpg')}" alt="portrait" />
</span>
</div>
<div class="slds-media__body">
<p class="slds-text-heading--label">Admin</p>
<h1 class="slds-text-heading--medium">MongoDB Databases</h1>
</div>
</div>
<!-- / MEDIA OBJECT -->
<!-- /HEADING AREA -->
</div>
<!-- GRID COL -->
<div class="slds-col slds-no-flex slds-align-middle">
<!--
<div class="slds-button-group" role="group">
<button class="slds-button slds-button--neutral">
New Account
</button>
<button class="slds-button slds-button--neutral">
More
</button>
</div>
-->
</div>
<!-- / GRID COL -->
</div>
<!-- / LAYOUT GRID -->
<p class="slds-text-body--small slds-m-top--x-small">hiccupcard.com</p>
</div>
<!-- / PAGE HEADER -->
<!-- PRIMARY CONTENT WRAPPER -->
<div class="myapp">
<!-- CREATE NEW ACCOUNT -->
<div aria-labelledby="newaccountform">
<!-- BOXED AREA
<fieldset class="slds-box slds-theme--default slds-container--small">
<legend id="newaccountform" class="slds-text-heading--medium slds-p-vertical--medium">Add a new account</legend>
<!-- CREATE NEW ACCOUNT FORM
<form class="slds-form--stacked">
<div class="slds-form-element">
<label class="slds-form-element__label" for="accountName">Name</label>
<div class="slds-form-element__control">
<input id="accountName" class="slds-input" type="text" placeholder="New account"/>
</div>
</div>
<button class="slds-button slds-button--brand slds-m-top--medium" type="button" onClick="createAccount()">Create Account</button>
</form>
<!-- CREATE NEW ACCOUNT FORM
</fieldset>
<!-- / BOXED AREA -->
</div>
<!-- / CREATE NEW ACCOUNT -->
<!-- ACCOUNT LIST TABLE -->
<div id="accountList" class="slds-p-vertical--medium"></div>
<!-- / ACCOUNT LIST TABLE -->
</div>
<!-- / PRIMARY CONTENT WRAPPER -->
<!-- FOOTER -->
<footer role="contentinfo" class="slds-p-around--large">
<!-- LAYOUT GRID -->
<div class="slds-grid slds-grid--align-spread">
<p class="slds-col">Salesforce-MongoDB Integration Example by Muralidhar.</p>
<p class="slds-col">© inteygrate.com</p>
</div>
<!-- / LAYOUT GRID -->
</footer>
<!-- / FOOTER -->
</div>
<!-- / REQUIRED SLDS WRAPPER -->
</body>
<!-- JAVASCRIPT -->
<script>
var account = new SObjectModel.Account();
var outputDiv = document.getElementById("accountList");
var dbs={};
<apex:repeat value="{!mongodbs}" var="db">
dbs['{!db.name}'] = '{!db.sizeOnDisk}';
console.log('{!db.name}');
</apex:repeat>
//console.log(issues);
function updateOutputDiv() {
var html = '<div class="slds-scrollable--x"><table class="slds-table slds-table--bordered">';
html += '<th scope="col">Database</th>';
html += '<th scope="col">Size</th></tr></thead><tbody>';
for (var db in dbs) {
html += '<tr><td>' + db + '</td>';
html += '<td>' + dbs[db] + '</td></tr>';
};
html = html + '</tbody></table></div>';
outputDiv.innerHTML = html;
}
updateOutputDiv();
</script>
<!-- / JAVASCRIPT -->
</html>
</apex:page>