AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

クイック スタート

このガイドでは、.NET/C# ドライバー を使用して MongoDB Atlas クラスターに接続するアプリケーションを作成する方法について説明します。別のドライバーまたはプログラミング言語を使用して MongoDB に接続する場合は、公式 MongoDB ドライバーのリストを参照してください。

.NET/C# ドライバーを使用すると、.NET アプリケーションから MongoDB クラスターに接続して通信できます。

MongoDB Atlas は、MongoDB クラスターでデータをホストする完全管理クラウドデータベース サービスです。このガイドでは、独自の無料クラスター(クレジットカードは不要)を開始する方法を説明します。

.NET アプリケーションを MongoDB Atlas クラスターに接続するには、以下の手順に従います。

このガイドに必要な Atlas 無料階層クラスターをセットアップするには、 MongoDB Atlas セットアップのガイドを完了させてください。

Atlas ガイドの手順を完了すると、Atlas に新しい MongoDB クラスターが配置され、新しいデータベースユーザーが作成され、クラスターにサンプル データセットがロードされます。また、コピー バッファには次のような接続文字列があります。

"mongodb+srv://<db_username>:<db_password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority"

コマンドプロンプトで次のコードを実行して、MongoDB 接続文字列を環境変数に保存します。この方法は、ソースコードに認証情報を含めるよりも安全です。

export MONGODB_URI="<your MongoDB URI>"

注意

PowerShell 環境変数

Microsoft PowerShell を使用している場合は、次のコマンドを実行して接続文字列を環境変数に保存します。

set MONGODB_URI="<your MongoDB URI>"

重要

接続stringの <db_username> セクションと <db_password> セクションを、 Atlasデータベースユーザーのユーザー名とパスワードに置き換えてください。

接続文字列の詳細については、「接続文字列」を参照してください。

次のように、新しいディレクトリを作成し、dotnet new コマンドを使用してプロジェクトを初期化します。

mkdir csharp-quickstart
cd csharp-quickstart
dotnet new console

dotnet add コマンドを使用して、.NET/C# ドライバーを依存関係としてプロジェクトに追加します。

dotnet add package MongoDB.Driver

次のコードをコピーして、アプリケーション内の Program.csファイルに貼り付けます。ドキュメントのクエリに、BsonDocument または Plain Old CLR Object(POCO)を使用することを選択できます。各アプローチの例を表示するには、対応するタブを選択します。

using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{
Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/ja-jp/docs/drivers/csharp/current/get-started/create-connection-string");
Environment.Exit(0);
}
var client = new MongoClient(connectionString);
var collection = client.GetDatabase("sample_mflix").GetCollection<BsonDocument>("movies");
var filter = Builders<BsonDocument>.Filter.Eq("title", "Back to the Future");
var document = collection.Find(filter).First();
Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{
Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/ja-jp/docs/drivers/csharp/current/get-started/create-connection-string");
Environment.Exit(0);
}
var client = new MongoClient(connectionString);
var collection = client.GetDatabase("sample_mflix").GetCollection<Movie>("movies");
var filter = Builders<Movie>.Filter.Eq(m => m.Title, "Back to the Future");
var movie = collection.Find(filter).First();
Console.WriteLine($"Title: {movie.Title}");
Console.WriteLine($"Plot: {movie.Plot}");
Console.WriteLine($"Genres: {string.Join(", ", movie.Genres ?? [])}");
[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string? Title { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("genres")]
public List<string>? Genres { get; set; }
}

Tip

.NET/ C#ドライバーで POCO を使用する方法の詳細については、POCOガイド を参照してください。

次のコマンドを使用して、コマンドラインからアプリケーションを実行します。

dotnet run csharp-quickstart.csproj

出力には、検索された 映画ドキュメントの詳細が含まれます。以下は、各アプローチの 出力を示しています。

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}
Title: Back to the Future
Plot: A young man is accidentally sent 30 years into the past...
Genres: Adventure, Comedy, Sci-Fi

Tip

エラーが発生した場合や出力が表示されない場合は、適切な接続文字列が指定され、サンプルデータがロードされていることを確認してください。

この手順を完了すると、.NET/C# ドライバーを使用して MongoDB クラスターに接続し、サンプル データに対してクエリを実行し、結果を出力する動作するアプリケーションが作成されます。

.NET/C# ドライバーを使用して Atlas に接続する方法について詳しくは、Atlas ドライバー接続ガイドを参照し、Select your language ドロップダウンで C# を選択してください。

CRUD 操作ガイドでは、.NET/C# ドライバーを使用してデータを読み取って変更する方法、または使用例では、一般的な操作を実行する方法を学習します。