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

适用对象: MongoDB

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

注意

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

API for MongoDB 参考文档 | MongoDB 包 (NuGet)

命名集合

在 Azure Cosmos DB 中,集合类似于关系数据库中的表。 创建集合时,集合名称会构成用于访问集合资源和任何子文档的 URI 段。

下面是命名集合时的一些快速规则:

  • 将集合名称的长度保持在 3 到 63 个字符之间
  • 集合名称只能包含小写字母、数字或短划线 (-) 字符。
  • 容器名称必须以小写字母或数字开头。

获取集合实例

使用 Collection 类的实例访问服务器上的集合。

以下代码片段假设你已经创建客户端连接

创建集合

若要创建集合,请将文档插入到集合中。

// insert one document
var product = new BsonDocument
{
    { "name", "Sand Surfboard" },
    { "category", "gear-surf-surfboards" },
    { "count", 1 }
};

client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertOne(product);

// insert many documents
var products = new List<BsonDocument>() 
{
    new BsonDocument
    {
        { "name", "Sand Surfboard" },
        { "category", "gear-surf-surfboards" },
        { "count", 1 }
    },
    new BsonDocument
    {
        { "name", "Ocean Surfboard" },
        { "category", "gear-surf-surfboards" },
        { "count", 5 }
    }
};

client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertMany(products);

删除集合

从数据库中删除集合以将其永久删除。 但是,访问集合的下一个插入或更新操作将创建一个具有该名称的新集合。

client.GetDatabase("adventureworks").DropCollection("products");

获取集合索引

MongoDB 查询引擎使用索引来提高数据库查询的性能。

var indexes = client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").Indexes;

var count = 0;
using (var cursor = await indexes.ListAsync())
{
    do
    {
        if (cursor.Current != null)
        {
            foreach (var index in cursor.Current)
            {
                Console.WriteLine(cursor.Current);
                count++;
            }
        }
    }
    while (await cursor.MoveNextAsync());
}

另请参阅