使用 JavaScript 在 Azure Cosmos DB for MongoDB 中管理文档
适用对象: MongoDB
通过插入、更新和删除文档的功能来管理 MongoDB 文档。
注意
示例代码片段在 GitHub 上作为 JavaScript 项目提供。
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 的值。
使用 ID 查询文档:
const query = { _id: ObjectId("62b1f43a9446918500c875c5")};
更新文档
要更新文档,请指定用于查找文档的查询以及应更新的文档的一组属性。 可以选择更新插入文档,如果文档不存在则插入该文档。
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 的批量写入。
可以使用以下批量操作:
MongoClient.Db.Collection.bulkWrite
- insertOne
- updateOne
- updateMany
- deleteOne
- deleteMany
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: 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