Creating a Document Collection with SODA for In-Database JavaScript

How to use SODA for In-Database JavaScript to create a new document collection is explained.

Collections allow you to logically group documents. Before a collection can be created or accessed, a few more steps must be completed unless you make use of the global soda object. Begin by creating a connection object. The connection object is the starting point for all SODA interactions in the MLE JavaScript module:

// get a connection handle to the database session
const connection = oracledb.defaultConnection();

Once the connection is obtained, you can use it to call Connection.getSodaDatabase(), a prerequisite for creating the collection:

// get a SODA database
const db = connection.getSodaDatabase();

With the SODA database available, the final step is to create the collection. Note that collection names are case-sensitive:

// Create a collection with the name "MyCollection".
// This creates a database table, also named "MyCollection",
// to store the collection. If a collection with the same name
// exists, it will be opened
const col = db.createCollection("MyCollection");

The preceding statement creates a collection that, by default, allows JSON documents to be stored. If the collection name passed to SodaDatabase.createCollection() is that of an existing collection, it will simply be opened. You can alternatively open a known, existing collection using SodaDatabase.openCollection().

Unless custom metadata is provided to SodaDatabase.createCollection() (which is not recommended), default collection metadata will be supplied. The default metadata has the following characteristics:

  • Each document in the collection has these components:
    • Key
    • Content
    • Version
  • The collection can store only JSON documents.
  • Document keys and version information are generated automatically.

Optional collection metadata can be provided to the call to createCollection(), however, the default collection configuration is recommended in most cases.

If a collection with the same name already exists, it is simply opened and its object is returned. If custom metadata is passed to the method and does not match that of the existing collection, the collection is not opened and an error is raised. To match, all metadata fields must have the same values.

See Also:

Oracle AI Database Introduction to Simple Oracle Document Access (SODA) for more details about collection metadata, including custom metadata.