SODA for In-Database JavaScriptによるコレクション内のドキュメントの置換
コレクション内の1つのドキュメントのコンテンツを別のドキュメントのコンテンツで置き換えるには、まずそのキーを使用して、変更するドキュメントを検索します。SodaOperation.key()は非ターミナル操作であるため、コンテンツを置換する最も簡単な方法は、SodaOperation.key()をSodaOperation.replaceOne()またはSodaOperation.replaceOneAndGet()につなげることです。
SodaOperation.replaceOne()はドキュメントを置換するのみですが、SodaOperation.replaceOneAndGet()はドキュメントを置換し、コール元にその結果の新しいドキュメントを提供します。
SodaOperation.replace()とSodaOperation.save()の違いは、キーがコレクションにまだ存在しない場合、後者では挿入を実行することです。置換操作では、SodaOperation.key()メソッドによる検索で既存のドキュメントを見つける必要があります。
ノート:
一部のバージョン生成メソッドは、ドキュメント・コンテンツのハッシュ値を生成します。このような場合、ドキュメント・コンテンツが変更されないと、バージョンも変更されません。
例8-15 コレクション内のドキュメントの置換および結果ドキュメントの戻し
この例は、コレクション内のドキュメントを置換し、変更されたドキュメントへの参照を戻す方法を示しています。従業員206に100単位の昇給が与えられているとします。SODA APIを使用して、次のように給与を更新できます:
export function replaceExample(){
// open employeesCollection in preparation of the update
const col = soda.openCollection('employeesCollection');
if (col === null){
throw new Error("'employeesCollection does not exist");
}
try{
// look up employeeId 206 using a QBE and get the document.
// Since the documents are inserted into the collection based
// on the HR.employees table, it is certain that there is at
// most 1 document with employeeId 206
const employeeDoc = col
.find()
.filter({"_id": 206})
.getOne();
// get the document's actual contents/payload
employee = employeeDoc.getContent();
// currently it is not possible to include the _id together with
// the replacement payload. This means existing _id must be deleted.
// The document, once replaced in the collection, will have its
// _id injected from the target document
delete employee_id;
// increase the salary
employee.salary += 100;
// save the document back to the collection. Note that you need
// to provide the document's key rather than a QBE or else an
// ORA-40734: key for the document to replace must be specified
// using the key attribute error will be thrown
const resultDoc = col
.find()
.key(employeeDoc.key)
.replaceOneAndGet(employee);
// print some metadata (note that content is not returned for
// performance reasons)
console.log(`Document updated successfully:
- key: ${resultDoc.key}
- version: ${resultDoc.version}`);
} catch(err){
console.log(`error modifying employee 206's salary: ${err}`);
}
}
この例で使用されているemployeesCollectionの作成方法の詳細は、例8-8を参照してください。
ノート:
パフォーマンス上の理由から、実際のドキュメントのコンテンツは戻されないため、変更されたコンテンツを読み取ろうとするとエラーが発生します。