MongoDB操做集

 

官网html

https://www.mongodb.com/download-center#communitymongodb

基本资料:数据库

http://www.runoob.com/mongodb/mongodb-intro.htmlwindows

下载地址:dom

https://www.mongodb.com/download-center/community异步

 

windows安装:ui

安装过程the domain,user name and/or password are incorrect.remember to use "." for the domain if the account is on the local machinespa

处理办法:取消从新安装code

 

使用:htm

与MongoDB通信的API类库:

咱们将使用由MongoDB官方提供的API类库来与MongoDB进行通信与交互,在Lezhima.Data项目中可经过NuGet管理器引用以下两个类库:

一、MongoDB.Bson

二、MongoDB.Driver

当插入数据时,若是不存在该数据库则自动建立一个新的数据库,若是不存在该集合则会自动建立一个集合

// 使用链接字符串链接
            var client = new MongoClient("mongodb://localhost:27017");
            // 制定多个地址和端口,让程序自动选择一个进行链接。
            //var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");
            //获取数据库
            var database = client.GetDatabase("foo");
            //获取数据集Collection
            var collection = database.GetCollection<BsonDocument>("bar");
            //插入数据
            var document = new BsonDocument {
                { "name", "MongoDB" },
                { "type", "Database" },
                { "count", 1 },
                { "info", new BsonDocument { { "x", 203 }, { "y", 102 } } }
            };
            //InsertOne(同步插入):
            collection.InsertOne(document);
            //InsertOneAsync(异步插入):
            await collection.InsertOneAsync(document);

//同步获取数量

 var count = collection.Count(new BsonDocument());

//异步获取集合数量

var count = await collection.CountAsync(new BsonDocument());

//读取信息

var documents = collection.Find(new BsonDocument()).ToList();

若是返回的数据预期很大,建议采用如下异步的迭代的方法处理。

await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d));

若是是在要用同步的方法,那么能够使用ToEnumerable适配器方法(数据量大的状况):

var cursor = collection.Find(new BsonDocument()).ToCursor();
 string aa = "";
foreach (var document in cursor.ToEnumerable()) {
                aa += document + ",";
}

用过滤器筛选获取单个数据

var filter = Builders<BsonDocument>.Filter.Eq("i", 71);

相关文章
相关标签/搜索