次の方法で共有


.NET を使って Azure Cosmos DB for MongoDB でコレクションを管理する

適用対象: MongoDB

ネイティブ MongoDB クライアント ドライバーを使って、Azure Cosmos DB に格納された MongoDB コレクションを管理します。

注意

コード スニペットの例は、.NET プロジェクトとしてGitHub 上で使用できます。

MongoDB 用 API リファレンス ドキュメント | MongoDB パッケージ (NuGet)

コレクションの名前付け

Azure Cosmos DB では、コレクションはリレーショナル データベースのテーブルに似ています。 コレクションを作成すると、コレクション名によって、コレクション リソースと子項目へのアクセスに使用される URI のセグメントが形成されます。

コレクション インスタンスの取得

サーバー上のコレクションにアクセスするには、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());
}

関連項目