Use MongoDB API with Oracle Autonomous Database on Dedicated Exadata Infrastructure

Oracle Database API for MongoDB translates the MongoDB wire protocol into SQL statements that are executed by Oracle Database. It lets developers who have MongoDB skill sets write JSON document-store applications for Oracle Database that use drivers and tools that understand the MongoDB protocol. See Overview of Oracle Database API for MongoDB in Oracle Database API for MongoDB for a detailed overview of this API.

Enable MongoDB API

You can enable the MongoDB API for an Autonomous Database from the OCI console or manually using Oracle REST Data Services (ORDS).

To use the MongoDB API with an Autonomous Database, you must install and configure customer managed Oracle REST Data Services (ORDS) separately, and the version of ORDS must be 22.3 or later. See Oracle API for MongoDB Support in Oracle REST Data Services Installation and Configuration Guide for the architectural concepts of this API.

To enable the MongoDB API from the OCI console:
  • On the Autonomous Database Details page, select the Tool configuration tab.
  • Click Edit tool configuration.
  • In the MongoDB API row, select in the Enable tool column to show Enabled.
  • Click Apply.
The Lifecycle state changes to updating until MongoDB is enabled.

You can also enable the MongoDB API when you provision or clone an instance by selecting Show advanced options and selecting the Tools tab.

To enable MongoDB manually:

For a demonstration of the above steps, refer to Getting Started in Oracle REST Data Services Installation and Configuration Guide.

Connect MongoDB Applications

After MongoDB API is enabled, you can create a MongoDB user and connect to Autonomous Database with its connection string.

With the MongoDB API connection string you can use the MongoDB Shell, which is a command-line utility, to connect and query your data.

You can retrieve its connection string from the Oracle Cloud Infrastructure Console. To retrieve the MongoDB API connection string:
  1. On the Autonomous Database Details page, select the Tool configuration tab.
  2. In the MongoDB API row, under Access URL click Copy.

If you’re using MongoDB API on Autonomous Database on Exadata Cloud@Customer, your network/DNS team must ensure that any MongoDB connection string hostname resolves to the cluster’s SCAN. Without this, MongoDB clients won’t be able to connect to the database. You can either allow connections to all the Autonomous Databases within the cluster using Wildcard DNS record or allow for a specific Autonomous Database:

Test MongoDB Connections

Create a Test Autonomous Database User for MongoDB

You can create a test user, or a similarly authenticated user, for testing purposes.

  1. Open the OCI Console for your Autonomous Database.
  2. Click Database Actions.
  3. From the Database Actions Launchpad, click Administration > Database Users.
  4. Click + Create User on the Database Users page.
  5. Enter a User Name and Password for your test user. Click Web Access, and set the Quota on tablespace DATA.
  6. Click the Granted Roles tab.
  7. In addition to the default roles, select and add the SODA_APP role for the user.
  8. Click Create User.

Test Connection Using the Command Line

  1. Login as the test user. Follow the steps in the previous example for instructions.
    $ mongosh --tls --tlsAllowInvalidCertificates 'mongodb://TESTUSER:<PASSWORD>@<database URL>.
    <OCI region>.oraclecloudapps.com:27017/admin?authMechanism=PLAIN&authSource=$external&ssl=true&loadBalanced=false'
    Current Mongosh Log ID: 614c9e2a01e3575c8c0b2ec7
    Connecting to:         mongodb://TESTUSER:<PASSWORD>@<database URL>.<OCIregion>.oraclecloudapps.com:27017/admin?
    authMechanism=PLAIN&authSource=$external&tls=true&loadBalanced=false
    Using MongoDB:                   3.6.2
    Using Mongosh:                   1.0.7
    For mongosh info see: https://docs.mongodb.com/mongodb-shell/admin
    > show dbs
    testuser    0 B
    > 

    Note:

    Use URI percent-encoding to replace any reserved characters in your connection-string URI — in particular, characters in your username and password. These are the reserved characters and their percent encodings:

    ! # $ % & ' ( ) * +
    %21 %23 %24 %25 %26 %27 %28 %29 %2A %2B
    , / : ; = ? @ [ ]
    %2C %2F %3A %3B %3D %3F %40 %5B %5D

    For example, if your username is RUTH and your password is @least1/2#? then your MongoDB connection string to server <server> might look like this:

    'mongodb://RUTH:%40least1%2F2%23%3F@<server>:27017/ruth/ ...'

    Depending on the tools or drivers you use, you might be able to provide a username and password as separate parameters, instead of as part of a URI connection string. In that case you likely won't need to encode any reserved characters they contain.

    See also:

  2. Create a collection and insert documents into your collection.
    testuser> show collections
    
    testuser> db.createCollection( 'fruit' )
    { ok: 1 }
    testuser> show collections
    fruit
    testuser> db.fruit.insertOne( {name:"orange", count:42} )
    {
      acknowledged: true,
      insertedId: ObjectId("614ca31fdab254f63e4c6b47")
    }
    testuser> db.fruit.insertOne( {name:"apple", count:12, color: "red"} )
    {
      acknowledged: true,
      insertedId: ObjectId("614ca340dab254f63e4c6b48")
    }
    testuser> db.fruit.insertOne( {name:"pear", count:5} )
    {
      acknowledged: true,
      insertedId: ObjectId("614ca351dab254f63e4c6b49")
    }
    testuser>
  3. Query the collection using a SQL client such as Database Actions.
    SELECT
         f.json_document.name, 
         f.json_document.count, 
         f.json_document.color
    FROM fruit f;

Test Connection Using a Node.js Application

  1. Download Node.js. If you have already downloaded or installed Node.js for your environment, you can skip this step.

    $ wget https://nodejs.org/dist/latest-v14.x/node-v14.17.5-linux-x64.tar.xz
  2. Extract the contents of the Node,js archive. If you have already downloaded or installed Node.js for your environment, you can skip this step.

    $ tar -xf node-v14.17.5-linux-x64.tar.xz
  3. Configure the PATH environment variable. If you have already downloaded or installed Node.js for your environment, you can skip this step.

    $ export PATH="`pwd`"/node-v14.17.5-linux-x64/bin:$PATH
  4. Test your connection with a Javascript example.

    1. Create a new directory.

      $ mkdir autonomous_mongodb
      $ cd autonomous_mongodb
      $ npm init –y
    2. Install mongodb dependency.

      $ npm install mongodb
    3. Create a JavaScript application named connect.js.

      const { MongoClient } = require("mongodb");
      const uri =
         "mongodb://TESTUSER:<PASSWORD>@<Database URI>.<OCI region>.oraclecloudapps.com:27017/admin?authMechanism=PLAIN&authSource=$external&ssl=true&loadBalanced=false";
      
      const client = new MongoClient(uri);
      
      async function run() {
        try {
              await client.connect();
      
              const database = client.db('admin');
              const movies = database.collection('movies');
      
              // Insert a movie
              const doc = { title: 'Back to the Future', 
                            year: 1985, genres: ['Adventure', 'Comedy', 'Sci-Fi'] }
              const result = await movies.insertOne(doc);
      
              // Query for a movie that has the title 'Back to the Future' :)
              const query = { title: 'Back to the Future' };
              const movie = await movies.findOne(query);
      
              console.log(movie);
        } finally {
           // Ensures that the client will close when you finish/error
           await client.close();
        }
      }
      run().catch(console.dir);
      

      Note:

      Use URI percent-encoding to replace any reserved characters in your connection-string URI — in particular, characters in your username and password. These are the reserved characters and their percent encodings:

      ! # $ % & ' ( ) * +
      %21 %23 %24 %25 %26 %27 %28 %29 %2A %2B
      , / : ; = ? @ [ ]
      %2C %2F %3A %3B %3D %3F %40 %5B %5D

      For example, if your username is RUTH and your password is @least1/2#? then your MongoDB connection string to server <server> might look like this:

      'mongodb://RUTH:%40least1%2F2%23%3F@<server>:27017/ruth/ ...'

      Depending on the tools or drivers you use, you might be able to provide a username and password as separate parameters, instead of as part of a URI connection string. In that case you likely won't need to encode any reserved characters they contain.

      See also:

    4. Run the example. The output should look similar to the following.

      $ node connect
      {
        _id: new ObjectId("611e3266005202371acf27c1"),
        title: 'Back to the Future',
        year: 1985,
        genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ]
      }