前言
距离上一次写博客,已经不记得大概有多长时间了, 是时候继续前行了...
MongoStudio 是一个Web的 MongoDB可视化操作工具, 一年半前已经写好, 但是总觉得不足, 现从头开始...
- 语言: C#
- 驱动: MongoDB C# 2.2 Driver
- 支持: MongoDB 3.4 及之前版本
基础
建立数据库链接
// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
var client = new MongoClient();
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");
获取数据库
var database = client.GetDatabase("foo");
获取表
var collection = database.GetCollection<BsonDocument>("bar");
进阶
列出数据库集合
using (var cursor = client.ListDatabases())
{
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString());
}
}
MongoDB C# 2.2 Driver 同时也提供了异步方法, 下文将不再给出异步代码, 同步异步区别后续开新文讲。
using (var cursor = await client.ListDatabasesAsync())
{
await cursor.ForEachAsync(document => Console.WriteLine(document.ToString()));
}

列出指定数据库的所有表
using (var cursor = database.ListCollections())
{
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString());
}
}

列出指定表的所有数据
var cursor = collection.Find(new BsonDocument());
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString());
}

列出指定表的所有索引
#region 列出指定表的所有索引
using (var cursor = collection.Indexes.List())
{
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString());
}
}
#endregion

今天就到这里了,本篇是基础。示例代码
参考
https://mongodb.github.io/mongo-csharp-driver/2.2/getting_started/