Inserting Documents into Collections with SODA for In-Database JavaScript

SodaCollection.insertOne() or a related call such as sodaCollection.insertOneAndGet() offers convenient ways to add documents to a collection. These methods create document keys automatically, unless the collection is configured with client-assigned keys and the input document provides the key, which is not recommended for most users.

SodaCollection.insertOne() simply inserts the document into the collection, whereas SodaCollection.insertOneAndGet() additionally returns a result document. The resulting document contains the document key and any other generated document components, except for the actual document’s content (this is done to improve performance).

Both methods automatically set the document's version, unless the collection has been created with custom metadata. Custom metadata might not include all the default metadata. When querying attributes not defined by the collection a null value is returned.

Note:

If you want the input document to replace the existing document instead of causing an exception, see Saving Documents into Collections with SODA for In-Database JavaScript.

Example 8-7 Inserting a SODA Document into a Collection

This example demonstrates how to insert a document into a collection using SodaCollection.insertOne().

export function insertOneExample() {

  // define the document's contents
  const payload = {
    "_id": 100,
    "job_id": "AD_PRES",
    "last_name": "King",
    "first_name": "Steven",
    "email": "SKING",
    "manager_id": null,
    "department_id": 90
  };

  // create or open the collection to hold the document
  const col = soda.createCollection("MyCollection");

  col.insertOne(payload);
}

Example 8-8 Inserting an Array of Documents into a Collection

This example demonstrates the use of SodaCollection.insertMany() to insert multiple documents with one command. The example essentially translates the relational table HR.employees into a collection.

export function insertManyExample() {

  // select all records from the hr.employees table into an array
  // of JavaScript objects in preparation of a call to insertMany
  const result = session.execute(
    `SELECT
       employee_id "_id",
       first_name "firstName",
       last_name "lastName",
       email "email",
       phone_number "phoneNumber",
       hire_date "hireDate",
       job_id "jobId",
       salary "salary",
       commission_pct "commissionPct",
       manager_id "managerId",
       department_id "departmentId"
     FROM
       hr.employees`,
     [],
     { outFormat: oracledb.OUT_FORMAT_OBJECT }
  );

  // create the collection and insert all employee records
  collection = soda.createCollection('employeesCollection');
  collection.insertMany(result.rows);

  // the MLE JavaScript SQL driver does not auto-commit
  session.commit();
}