Share via


使用 JavaScript 在 Azure Cosmos DB for MongoDB 中管理文件

適用於: MongoDB

使用插入、更新和刪除文件的功能來管理您的 MongoDB 文件。

注意

範例程式碼片段可在 GitHub 上以 JavaScript 專案形式取得。

API for MongoDB 參考文件 | 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,系統會為您建立一個識別碼作為 BSON 物件。 所提供識別碼的值是使用 ObjectId 方法存取。

使用識別碼來查詢文件:

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: 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

另請參閱