跟我一步一步写出MongoDB Web 可视化工具(二)

前言

上篇讲了一些基础,主要注重的是,包括建立数据库链接、获取数据库、获取表、列出数据库、列出表、列出索引、获取数据等。

本篇依然是基础,注重增改删,废话不多说,咱们开始。

进阶

创建一个数据库和一个集合

            #region 创建一个数据库和一个集合
            client.DropDatabase("NewDatabase"); // NewDatebase存在则删除NewDatebase
            database = client.GetDatabase("NewDatabase"); // 获取NewDatabase 创建collection时,NewDatabase不存在则自动创建
            database.DropCollection("NewCollection"); // NewCollection存在则删除NewCollection
            database.CreateCollection("NewCollection"); // 创建 NewCollection
            #endregion 

需要说明一点, 创建集合,可以设置集合一些项,关于CreateCollectionOptions 参考类说明了

var options = new CreateCollectionOptions { Capped = true, MaxSize = 1024 * 1024 };
database.CreateCollection("NewCollection1", options);

同时,MongoDB C# Driver 也提供了异步操作的方法,这里不赘述。

创建索引

collection.Indexes.CreateOne(new BsonDocument("newIndex", 1));
//or
var keys = Builders<BsonDocument>.IndexKeys.Ascending("newIndex");
collection.Indexes.CreateOne(keys);

执行指令

            var buildInfoCommand = new BsonDocumentCommand<BsonDocument>(new BsonDocument("buildinfo", 1));
            var result = database.RunCommand(buildInfoCommand);

其实, RunCommand方法执行指令,完全可以做到更多的事情。本篇源码

参考

https://mongodb.github.io/mongo-csharp-driver/2.2/getting_started/

http://stackoverflow.com/questions/33440956/mongodb-c-sharp-driver-runcommandasync

原文地址:https://www.cnblogs.com/jackbase/p/6601044.html