For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Connect to MongoDB by Using a JNDI Datasource

In this guide, you can learn how to connect the MongoDB Java driver to your MongoDB instance by using a Java Naming and Directory Interface (JNDI) Datasource.

MongoClientFactory includes a JNDI ObjectFactory implementation that returns MongoClient instances based on a connection URI. Consult the following guides to learn how to configure your application to connect using a JNDI Datasource.

  1. In a Wildfly installation, create a new module for MongoDB at modules/system/layers/base/org/mongodb/main. Copy the following jar files into the module:

    • mongodb-driver-sync-5.13.0.jar

    • mongodb-driver-core-5.13.0.jar

    • bson-5.13.0.jar

    • bson-record-codec-5.13.0.jar

    Add the following module.xml file into the module:

    module.xml
    <module xmlns="urn:jboss:module:1.9" name="org.mongodb">
    <resources>
    <resource-root path="bson-5.13.0.jar"/>
    <resource-root path="bson-record-codec-5.13.0.jar"/>
    <resource-root path="mongodb-driver-core-5.13.0.jar"/>
    <resource-root path="mongodb-driver-sync-5.13.0.jar"/>
    </resources>
    <dependencies>
    <module name="javax.api"/>
    <module name="javax.transaction.api"/>
    <module name="javax.servlet.api" optional="true"/>
    </dependencies>
    </module>
  2. Add a binding to the naming subsystem configuration that references the preceding module, the MongoClientFactory class, and the connection string for the MongoDB cluster.

    <subsystem xmlns="urn:jboss:domain:naming:2.0">
    <bindings>
    <object-factory name="java:global/MyMongoClient" module="org.mongodb" class="com.mongodb.client.MongoClientFactory">
    <environment>
    <property name="connectionString" value="<connection string uri>"/>
    </environment>
    </object-factory>
    </bindings>
    <remote-naming/>
    </subsystem>

    Note

    Replace the placeholder connection value in the property tag with a value that points to your MongoDB installation.

This makes a MongoClient instance discoverable through the JNDI name MyMongoClient in the java:global context.

Tip

For JNDI implementations other than those listed here, you can create your own Factory wrapper based on the driver's built-in MongoClientFactory implementation.

Rate this page

On this page