Tool:Visual Studio 2015 Enterprise Update 1
DB:MongoDB 3.2
OS:Windows 10
C#
以下為測試使用C#存取MongoDB的小筆記。要使用MongoDB之前,需要先安裝MongoDB環境,可以參考這篇文章。
使用Visual Studio 2015 建立一個Console程式。
使用Package Manager Console工具安裝套件
Install-Package MongoDB.Driver -Version 2.2.3
Visual Studio 會安裝相依套件如下:接下來只要將官網提供的片段範例程式加到專案之中,補幾個字:
using System;
using MongoDB.Bson;
using MongoDB.Driver;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
QueryData();
Console.ReadLine();
}
static async void QueryData()
{
IMongoClient _client = new MongoClient();
IMongoDatabase _database = _client.GetDatabase("test");
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var count = 0;
using (var cursor = await collection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
count++;
}
}
}
Console.WriteLine($"Count : {count}");
}
}
}
using MongoDB.Bson;
using MongoDB.Driver;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
QueryData();
Console.ReadLine();
}
static async void QueryData()
{
IMongoClient _client = new MongoClient();
IMongoDatabase _database = _client.GetDatabase("test");
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var count = 0;
using (var cursor = await collection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
count++;
}
}
}
Console.WriteLine($"Count : {count}");
}
}
}
按CTRL + F5執行專案,得到執行結果如下:
沒有留言:
張貼留言