Share via


使用 JavaScript 在 Azure Cosmos DB for MongoDB 中管理集合

適用於: MongoDB

使用原生 MongoDB 用戶端驅動程式來管理儲存在 Azure Cosmos DB 中的 MongoDB 集合。

注意

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

API for MongoDB 參考文件 | MongoDB 套件 (npm)

為集合命名

在 Azure Cosmos DB 中,集合類似於關聯式資料庫中的資料表。 當您建立集合時,集合名稱會成為存取集合資源和任何子文件的 URI 區段。

以下是命名集合時的一些快速規則:

  • 集合名稱長度應為 3 到 63 個字元
  • 集合名稱只能包含小寫字母、數字或虛線 (-) 字元。
  • 容器名稱必須以小寫字母或數字開頭。

取得集合執行個體

使用 Collection 類別的執行個體來存取伺服器上的集合。

下列程式碼片段假設您已建立用戶端連線,而且您已在這些程式碼片段之後關閉用戶端連線

建立集合

若要建立集合,請將文件插入集合中。

// 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)}`);

卸除集合

從資料庫卸除集合,以永久移除集合。 不過,存取集合的下一個插入或更新作業將會使用該名稱建立新的集合。

// Drop the collection from the database, removing it permanently. 
// New accesses will create a new collection.

// drop from db instance
const dropCollection1 = await client.db("adventureworks").dropCollection("products");
console.log(`Collection dropped:\t${JSON.stringify(dropCollection1)}`);

// drop from collection instance
const dropCollection2 = await client.db("adventureworks").collection('products-2').drop();
console.log(`Collection dropped:\t${JSON.stringify(dropCollection2)}`);

上述程式碼片段會顯示下列範例主控台輸出:

Collection dropped:     true
Collection dropped:     true
done

取得集合索引

MongoDB 查詢引擎會使用索引來改善資料庫查詢的效能。

// Get all indexes in collection
const collectionInstance = await client.db("adventureworks").collection('products')
const indexes = await collectionInstance.indexes();
console.log(`Indexes on collection:\n${Object.keys(indexes).map(key => `\t${key}: ${JSON.stringify(indexes[key])}\n`)}`);

上述程式碼片段會顯示下列範例主控台輸出:

Indexes on collection:
        0: {"v":1,"key":{"_id":1},"name":"_id_","ns":"adventureworks.products"}
,       1: {"v":1,"key":{"name":1},"name":"name_1","ns":"adventureworks.products"}

done

另請參閱