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

适用对象: MongoDB

使用本机 MongoDB 客户端驱动程序管理存储在 Azure Cosmos DB 中的 MongoDB 集合。

注意

示例代码片段在 GitHub 上作为 JavaScript 项目提供。

MongoDB API 参考文档 | 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

另请参阅