MongoDB操作集

 

官网

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

基本资料:

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

下载地址:

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

 

windows安装:

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

处理办法:取消重新安装

 

使用:

与MongoDB通讯的API类库:

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

1、MongoDB.Bson

2、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);

 

posted @ 2019-04-22 15:44  枫-  阅读(154)  评论(0编辑  收藏  举报