次の方法で共有


Azure Cosmos DB for MongoDB のドキュメントを JavaScript で管理する

適用対象: MongoDB

ドキュメントを挿入、更新、削除する機能を使って、MongoDB ドキュメントを管理します。

Note

コード スニペットの例は、JavaScript プロジェクトとして GitHub で入手できます。

MongoDB 用 API リファレンス ドキュメント | MongoDB パッケージ (npm)

ドキュメントの挿入

JSON スキーマで定義されたドキュメントをコレクションに挿入します。

// get database client for database
// if database or collection doesn't exist, it is created
// when the doc is inserted

// insert doc
const doc = { name: `product-${random}` };
const insertOneResult = await client
  .db('adventureworks')
  .collection('products')
  .insertOne(doc);
console.log(`Insert 1 - ${JSON.stringify(insertOneResult)}`);

// insert docs
const docs = [{ name: `product-${random}` }, { name: `product-${random}` }];
const insertManyResult = await client
  .db('adventureworks')
  .collection('products')
  .insertMany(docs);
console.log(`Insert many ${JSON.stringify(insertManyResult)}`);

上記のコード スニペットでは、次のようなコンソール出力例が表示されます。

Insert 1 - {"acknowledged":true,"insertedId":"62b2394be4042705f00fd790"}
Insert many {"acknowledged":true,"insertedCount":2,"insertedIds":{"0":"62b2394be4042705f00fd791","1":"62b2394be4042705f00fd792"}}
done

ドキュメント ID

ドキュメントに ID (_id) を指定しなかった場合は、BSON オブジェクトとして作成されます。 指定された ID の値は、ObjectId メソッドでアクセスできます。

ID を使って、ドキュメントのクエリを実行します。

const query = { _id: ObjectId("62b1f43a9446918500c875c5")};

ドキュメントの更新

ドキュメントを更新するには、ドキュメントの検索に使うクエリと、更新する必要があるドキュメントの一連のプロパティを指定します。 ドキュメントを upsert することも可能で、その場合、まだ存在しない場合にドキュメントを挿入します。

const product = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};

const query = { name: product.name };
const update = { $set: product };
const options = { upsert: true, new: true };

const upsertResult = await client
  .db('adventureworks')
  .collection('products')
  .updateOne(query, update, options);

console.log(
  `Upsert result:\t\n${Object.keys(upsertResult).map(key => `\t${key}: ${upsertResult[key]}\n`)}`
);

上記のコード スニペットでは、挿入のコンソール出力例として次のようなものが表示されます。

Upsert result:
        acknowledged: true
,       modifiedCount: 0
,       upsertedId: 62b1f492ff69395b30a03169
,       upsertedCount: 1
,       matchedCount: 0

done

上記のコード スニペットでは、更新のコンソール出力例として次のようなものが表示されます。

Upsert result:
        acknowledged: true
,       modifiedCount: 1
,       upsertedId: null
,       upsertedCount: 0
,       matchedCount: 1

done

コレクションの一括更新

bulkWrite 操作では、いくつかの操作を一度に実行できます。 Azure Cosmos DB の一括書き込みを最適化する方法を確認してください。

次のような一括操作が可能です。

const doc1 = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};
const doc2 = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 7',
  quantity: 5,
  sale: true,
};

// update docs with new property/value
const addNewProperty = {
  filter: { category: 'gear-surf-surfboards' },
  update: { $set: { discontinued: true } },
  upsert: true,
};

// bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany
const upsertResult = await client
  .db('adventureworks')
  .collection('products')
  .bulkWrite([
    { insertOne: { document: doc1 } },
    { insertOne: { document: doc2 } },
    { updateMany: addNewProperty },
  ]);

console.log(`${JSON.stringify(upsertResult)}`);

上記のコード スニペットでは、次のようなコンソール出力例が表示されます。

{
  "ok":1,
  "writeErrors":[],
  "writeConcernErrors":[],
  "insertedIds":[
    {"index":0,"_id":"62b23a371a09ed6441e5ee30"},
    {"index":1,"_id":"62b23a371a09ed6441e5ee31"}],
  "nInserted":2,
  "nUpserted":0,
  "nMatched":10,
  "nModified":10,
  "nRemoved":0,
  "upserted":[]
}
done

ドキュメントの削除

ドキュメントを削除するには、クエリを使ってドキュメントの検索方法を定義します。

const product = {
  _id: new ObjectId('62b1f43a9446918500c875c5'),
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};

const query = { name: product.name };

// delete 1 with query for unique document
const delete1Result = await client
  .db('adventureworks')
  .collection('products')
  .deleteOne(query);
console.log(
  `Delete 1 result:\t\n${Object.keys(delete1Result).map(key => `\t${key}: ${delete1Result[key]}\n`)}`
);

// delete all with empty query {}
const deleteAllResult = await client
  .db('adventureworks')
  .collection('products')
  .deleteMany({});
console.log(
  `Delete all result:\t\n${Object.keys(deleteAllResult).map(key => `\t${key}: ${deleteAllResult[key]}\n`)}`
);

上記のコード スニペットでは、次のようなコンソール出力例が表示されます。

Delete 1 result:
        acknowledged: true
,       deletedCount: 1

Delete all result:
        acknowledged: true
,       deletedCount: 27

done

関連項目