c#_使用官方驱动操作mongodb数据库
2015-12-27 22:20
706 查看
PS:大二学生,写写只是为了记录和发现,境界较低,不喜勿喷。
tips:假设你已经在 windows 下安装好了 mongodb 并且打开了数据库服务。(也就是说,你的 mongodb 能在 mongo shell 里跑了)
准备工作:下载 MongoDB .NET Driver == click here =>http://mongodb.github.io/mongo-csharp-driver/?_ga=1.231539542.892725284.1450600637 并将目录下的一下一个文件添加到引用在中
+ MongoDB.Driver.Legacy.dll
+ MongoDB.Driver.GridFS.dll
+ MongoDB.Driver.dll
+ MongoDB.Driver.Core.dll
+ MongoDB.Bson.dll
然后在代码中添加一下代码
using MongoDB.Driver
using MongoDB.Bson
至此,我们实际上已经连接好了本地的 mongodb 数据库,不需要配置 IP 和 端口号,这里这里都是使用默认的(做 demo)
插入数据的基本思路很简单,先使用 database.GetCollection(collectionName);来获取 collection 。之后就可以通过 InsertOne(document) 来插入数据了。
返回全部的数据
返回部分满足条件的数据
PS : C#访问 BsonDocument 是通过键值访问的,如果 doc 是一个 BsonDocument 对象,而 name 是这个对象中的一个键值,则 doc[name] 这可以访问 name 对应的数据。
PS : 其他查找操作,比如 内嵌对象的查找,对象中 array 中数据的查找,包括多个 condition 查找等,我在此就不一一列出了,可以参考:(https://docs.mongodb.org/getting-started/csharp/introduction/).++官方文档
这里,通过 filter 找到你要删除的数据,然后调用 DeleteManyAsync 方法删除数据。
这里唯一不同的是 UpdateOneAsync 这个函数有两个参数,第一个参数是我们通过 filter 查找到的需要更改的数据文档,然后 第二个参数是我们设置的新的 对象的值。
至此,已通过 mongodb 官方网站提供的驱动实现了基本对数据库各种基本的操作,其余方法等,等到了实际开发中再去发掘和使用。
tips:假设你已经在 windows 下安装好了 mongodb 并且打开了数据库服务。(也就是说,你的 mongodb 能在 mongo shell 里跑了)
准备工作:下载 MongoDB .NET Driver == click here =>http://mongodb.github.io/mongo-csharp-driver/?_ga=1.231539542.892725284.1450600637 并将目录下的一下一个文件添加到引用在中
+ MongoDB.Driver.Legacy.dll
+ MongoDB.Driver.GridFS.dll
+ MongoDB.Driver.dll
+ MongoDB.Driver.Core.dll
+ MongoDB.Bson.dll
然后在代码中添加一下代码
using MongoDB.Driver
using MongoDB.Bson
1.连接数据库
MongoClient client; MongoDatabase database; client = new MongoClient(); // 在shell下输入db可以查看当前正在使用的数据库名称 // 在shell下输入show dbs 可以查看当前所有的数据库名称 // 在shell下输入show collections 可以查看当前数据库的所有collection database = client.GetDatabase(Your_Database);
至此,我们实际上已经连接好了本地的 mongodb 数据库,不需要配置 IP 和 端口号,这里这里都是使用默认的(做 demo)
2.插入数据
public static void InsertBsonDocument(string collectionName) { // 获取集合 var collection = database.GetCollection<BsonDocument>(collectionName); // BsonDocument 对象 var document = new BsonDocument { { "address" , new BsonDocument { { "street", "2 Avenue" }, { "zipcode", "10075" }, { "building", "1480" }, { "coord", new BsonArray { 73.9557413, 40.7720266 } } } }, { "borough", "Manhattan" }, { "cuisine", "Italian" }, { "grades", new BsonArray { new BsonDocument { { "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) }, { "grade", "A" }, { "score", 11 } }, new BsonDocument { { "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) }, { "grade", "B" }, { "score", 17 } } } }, { "name", "Vella" }, { "restaurant_id", "41704620" } }; // 插入数据 collection.InsertOne(document); }
插入数据的基本思路很简单,先使用 database.GetCollection(collectionName);来获取 collection 。之后就可以通过 InsertOne(document) 来插入数据了。
3.查找数据
思路和上面的插入数据相同 , 也是先通过 GetCollection来获取 collection .然后查找返回全部的数据
public static async void QueryCollectionSome(string collectionName) { var collection = database.GetCollection<BsonDocument>(collectionName); // 相当于是一个过滤条件(这个过滤条件为空,如果使用这个过滤器,所有的数据都是表中的所有数据都是查找的返回结果) var filter = new BsonDocument(); // 使用await 等待查找结果返回,再继续执行 using (var cursor = await collection.FindAsync(filter)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (var document in batch) { Console.WriteLine(document.ToString()); } } } }
返回部分满足条件的数据
public static async Task<List<BsonDocument>> QueryCollection(string collectionName) { var collection = database.GetCollection<BsonDocument>(collectionName); var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan"); var list = await collection.Find(filter).ToListAsync(); // 打印返回对象中满足条件的数目 Console.WriteLine(list.Count()); return list; }
PS : C#访问 BsonDocument 是通过键值访问的,如果 doc 是一个 BsonDocument 对象,而 name 是这个对象中的一个键值,则 doc[name] 这可以访问 name 对应的数据。
PS : 其他查找操作,比如 内嵌对象的查找,对象中 array 中数据的查找,包括多个 condition 查找等,我在此就不一一列出了,可以参考:(https://docs.mongodb.org/getting-started/csharp/introduction/).++官方文档
4.删除数据
/// <summary> /// Remove All Documents That Match a Condition /// </summary> /// <param name="collectionName"></param> /// <returns></returns> public static async Task<DeleteResult> RemoveDateMatched(string collectionName) { var collection = database.GetCollection<BsonDocument>(collectionName); var builder = Builders<BsonDocument>.Filter; var filter = builder.Eq("adress.street", "3 Avenue"); // 删除多个数据 var result = await collection.DeleteManyAsync(filter); // 打印删除的数据的数目 Console.WriteLine(result.DeletedCount); return result; }
这里,通过 filter 找到你要删除的数据,然后调用 DeleteManyAsync 方法删除数据。
database.DropCollectionAsync(collectionName); // 这个方法可以直接删除一个 collection
5.更新数据(更改数据)
public static async Task<UpdateResult> UpdateOne(string collectionName) { var collection = database.GetCollection<BsonDocument>(collectionName); var filter = Builders<BsonDocument>.Filter.Eq("name", "Vella"); // set({里面是新的值}) var update = Builders<BsonDocument>.Update .Set("cuisine", "American (New)") .CurrentDate("lastModified"); // 修改之前的值 var a = await collection.Find(Builders<BsonDocument>.Filter.Eq("borough", "Manhattan")).ToListAsync(); foreach (var item in a) { // 这里涉及到BsonDocument的数据访问 Console.WriteLine(item["cuisine"].AsString); } // 执行更新操作 var result = await collection.UpdateOneAsync(filter, update); Console.WriteLine(result.ModifiedCount); a = await collection.Find(Builders<BsonDocument>.Filter.Eq("borough", "Manhattan")).ToListAsync(); // 显示更新之后的值 foreach (var item in a) { Console.WriteLine(item["cuisine"].AsString); } return result; }
这里唯一不同的是 UpdateOneAsync 这个函数有两个参数,第一个参数是我们通过 filter 查找到的需要更改的数据文档,然后 第二个参数是我们设置的新的 对象的值。
至此,已通过 mongodb 官方网站提供的驱动实现了基本对数据库各种基本的操作,其余方法等,等到了实际开发中再去发掘和使用。
相关文章推荐
- 每天200亿次查询 – MongoDB在奇虎360【转】
- Mongodb聚合
- 在yii中使用mongodb扩展
- MongoDB系列-初识MongoDB
- mongodb 在mac 系统上安装
- 使用node.js的第三方模块Mongoose访问mongodb(六)
- 安装MongoDB(做成Windows服务)并加载C#驱动程序
- mongodb初步
- MongoDB索引概述
- MongoDB 分片集群搭建
- MongoDB相关操作符
- Centos修炼-----> Centos7之Centos安装MongoDB
- mongoDB-学习-安装
- PHP7之Mongodb API使用详解
- 8天学通MongoDB——第八天 驱动实践
- 8天学通MongoDB——第七天 运维技术
- 8天学通MongoDB——第六天 分片技术
- 8天学通MongoDB——第五天 主从复制
- 8天学通MongoDB——第四天 索引操作
- 8天学通MongoDB——第三天 细说高级操作