【MongoDB】在C#中使用
一、MongoClient类
在2.10.0版本中引入了MongoClient类,同时在其API中也说明了Mongo类会在将来的版本中被MongoClient替换(Note: This class has been superseded by MongoClient
, and may be deprecated in a future release.)。故在这次调整中,也对原先的Mongodb部分做了相应的修改。
设置配置信息
//连接地址
private static string conn = "mongodb://192.168.11.51:40000";
//数据库名称
private static string dbName = "yan";
//集合名称
private static string colName = "Demo";
//连接服务端
static MongoClient client = new MongoClient(conn);
//获取指定数据库
static IMongoDatabase db = client.GetDatabase(dbName);
//获取指定集合 BsonDocument数据库文档对象
static IMongoCollection<BsonDocument> coll = db.GetCollection<BsonDocument>(colName);
使用Collection
Collection是文档(document)的集合,可以理解为我们的数据表。而每一个文档就是我们的一行数据。在MongoDB的驱动中,我们有两种方式来使用Collection:
- 使用 BsonDocument 模型
- 使用自定义的实体模型
如果我们的文档结构比较复杂,或者定义为实体模型比较困难,那么推荐使用BsonDocument模型。
如果我们的文档结构清晰,存储的字段也是固定的,那么推荐使用自定义的实体模型。实体对象的格式如下:
public class Entity
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
我们在获取Collection引用的时候,需要提供一个文档类型:var collection = db.GetCollection<Entity>("entities");
注意:用自定义类型的时候一定要有Id字段。
两种方式都可以使用,而且各有好处,通过自定义类型的方式,可以使得collection中的文档有比较统一的模式;
使用BsonDocument方式则可以支持更多的文档模式,也就是说如果一个collection中的文档拥有各种各样的模式,那么BsonDocument方式就会更灵活。
在有了Collection之后,我们可以写一个CURD的例子:
var collection = db.GetCollection<Entity>("entities"); var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id; var query = Query<Entity>.EQ(e => e.Id, id);
entity = collection.FindOne(query); entity.Name = "Dick";
collection.Save(entity); var update = Update<Entity>.Set(e => e.Name, "Harry");
collection.Update(query, update); collection.Remove(query);
二、BsonDocument对象
在MongoDB.Bson命名空间下存在一个BsonDocument类,它表示MongoDB的文档对象(二进制JSON),代表着MongoDB中不规则数据一条条实体模型。
可以使用BsonDocument对不规则数据进行操作,这个类型继承了IEnumberable<>类,也就是说有将每一个实体模型看做一个集合,我们可以使用下标方式获取实体模型中的值.
其部分定义:
//
// 摘要:
// Gets or sets a value by position.
//
// 参数:
// index:
// The position.
//
// 返回结果:
// The value.
public override BsonValue this[int index] { get; set; }
//
// 摘要:
// Gets or sets a value by name.
//
// 参数:
// name:
// The name.
//
// 返回结果:
// The value.
public override BsonValue this[string name] { get; set; }
//
// 摘要:
// Gets the value of an element or a default value if the element is not found.
//
// 参数:
// name:
// The name of the element.
//
// defaultValue:
// The default value to return if the element is not found.
//
// 返回结果:
// Teh value of the element or a default value if the element is not found.
[Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
public virtual BsonValue this[string name, BsonValue defaultValue] { get; }
其他参考:BSON
三、插入数据库
主要有:InsertOne、InsertMany
//1、插入一条
ModelTestOne modelTestOne = new ModelTestOne()
{
Age = ,
Name = "huhu",
Sex = "男"
}; //创建数据库链接
var client = new MongoClient(connectionString);
//获得数据库、集合
var database = client.GetDatabase(dataBaseName);
IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName);
colTemp.InsertOne(entity); //2、插入多条
var doc = new[]
{
new BsonDocument{
{ "DepartmentName","开发部"},
{ "People",new BsonArray
{
new BsonDocument{ { "Name", "狗娃" },{"Age", } },
new BsonDocument{ { "Name", "狗剩" },{"Age", } },
new BsonDocument{ { "Name", "铁蛋" },{"Age", } }
}
},
{"Sum", },
{ "dim_cm", new BsonArray { , } } },
new BsonDocument{
{ "DepartmentName","测试部"},
{ "People",new BsonArray
{
new BsonDocument{ { "Name", "张三" },{"Age", } },
new BsonDocument{ { "Name", "李四" },{"Age", } },
new BsonDocument{ { "Name", "王五" },{"Age", } }
}
}
,
{ "Sum", }
,
{ "dim_cm", new BsonArray { , } } },
new BsonDocument{
{ "DepartmentName","运维部"},
{ "People",new BsonArray
{
new BsonDocument{ { "Name", "闫" },{"Age", } },
new BsonDocument{ { "Name", "王" },{"Age", } },
new BsonDocument{ { "Name", "赵" },{"Age", } }
}
},
{ "Sum", },
{ "dim_cm", new BsonArray { 22.85, } } }
}; //创建数据库链接
var client = new MongoClient(connectionString);
//获得数据库、集合
var database = client.GetDatabase(dataBaseName);
IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName);
colTemp.InsertMany(entity);
四、更新数据库
文档更新的方法有两种,通过Save方法进行整个文档替换,或者通过Update方法进行文档的部分更新。
例如,找到sid为9,并且name为Will9的这个文档,把age字段更新为27
//Save()
var query = Query.And(Query.EQ("sid", ), Query.EQ("name", "Will9"));
BsonDocument Will9 = collection.FindOne(query);
if (Will9 != null)
{
Will9["age"] = ;
collection.Save(Will9);
} //Update()
var query = Query.And(Query.EQ("sid", ), Query.EQ("name", "Will9"));
var update = Update.Set("age", );
collection.Update(query, update);
五、删除某条记录
//删除特定条件的文档:
var query = Query.EQ("sid", );
collection.Remove(query); //删除所有文档:
collection.RemoveAll();
六、查询数据库
通过MongoDB driver,可以支持三种查询方法:QueryDocument、Query Builder、LINQ
public static Person Find(int id)
{
return mc.FindOneAs<Person>(Query.EQ("_id", id));
} public static MongoCursor<Person> FindAll()
{
return mc.FindAllAs<Person>();
} public static MongoCursor<Person> Select(QueryDocument q)
{
return mc.FindAs<Person>(q);
}
统计数据个数
public static long Count(QueryDocument q)
{
return mc.Count(q);
}
排序和分页
public static MongoCursor<Person> SkipAndLimit(int a, int b)
{
return mc.FindAllAs<Person>().SetSkip(a).SetLimit(b);
}
【MongoDB】在C#中使用的更多相关文章
- (转载)MongoDB C#驱动中Query几个方法
MongoDB C#驱动中Query几个方法 Query.All("name", "a", "b");//通过多个元素来匹配数组 Query ...
- 处理范例代码Webapi中的Mongodb的Bson中ObjectId反序列化异常
微软代码范例中的一个Bug 处理Mongodb的Bson中ObjectId反序列化异常 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/f ...
- MongoDB数据库设计中6条重要的经验法则
Part 1 原文:6 Rules of Thumb for MongoDB Schema Design: Part 1 By William Zola, Lead Technical Support ...
- MongoDB 在Node中的应用
转: MongoDB 在Node中的应用 文章目录 一 .什么是 MongoDB? 二.小Demo 三.Demo 增删改查 3.1 新增 3.2 查询 3.2.1 查询所有 [{},{}] 找不到返回 ...
- NoSql非关系型数据库之MongoDB应用(三):MongoDB在项目中的初步应用
业精于勤,荒于嬉:行成于思,毁于随. 我们可以结合相关的IDE做一个简单的增删改查了,实现MongoDB在项目中的初步应用. 前提是安装了MongoDB服务和MongoDB可视化工具,没有安装的可以点 ...
- 利用log4j+mongodb实现分布式系统中日志统一管理
背景 在分布式系统当中,我们有各种各样的WebService,这些服务可能分别部署在不同的服务器上,并且有各自的日志输出.为了方便对这些日志进行统一管理和分析.我们可以将日志统一输出到指定的数 ...
- mongodb在java中的查询
mongodb 根据_id 查询记录: public Price queryPriceById(String id) throws Exception { return mongoTemplate.f ...
- MongoDb Replica Set中使用的地址
Unable to connect to a member of the replica set matching the read preference Primary 今天尝试使用MongoDB ...
- 从MongoDB的ObjectId中获取时间信息
MongoDB默认使用_id字段作为主键,类型为ObjectId.ObjectId的生成有一定的规则,详情可以查看这篇文章 - MongoDB深究之ObjectId.如果你在写入数据库的时候忘记写入创 ...
- MongoDB使用过程中的一些问题
1.MongoDB配置修改不生效的问题:今天因为某个原因,需要修改mongodb的配置文件. 改完以后,在init.d里面restart命令重启server,后来stop又start重启server. ...
随机推荐
- condition的使用
condition 的作用:条件锁 需求: 按需执行三个线程. 用wait,notify的方式: /** * 有序线程 wait,notify版 */ public class OrderThread ...
- 图解javascript的this指向
图解javascript的this指向 作者: HerryLo 本文永久有效链接: https://github.com/AttemptWeb...... 以下就只有两张图,请放心食用!! #简版th ...
- C#学习笔记------参数
一.形参 形参是本地变量,它声明在方法的参数列表中,而不是方法体中.
- ADO,net 实体数据模型增、删、改,浅谈
第一步:建立ADO.net数据模型,一步步操作就行 第二步:画个简单的测试界面 第三步铺代码 using DevComponents.DotNetBar.SuperGrid; using DevCom ...
- Javascript实现的智能消防栓状态监测画面
系统需要添加智能消防栓模块.集成了一家采用NbIOT通讯的智能消防栓产品.由第厂家平台对接NbIot特联网平台,我们平台提供一个api从第三方平台接收消防栓状态,用SignlaR把状态推送到前端.需要 ...
- Dubbo的10种集群容错模式
学习Dubbo源码的过程中,首先看到的是dubbo的集群容错模式,以下简单介绍10种集群容错模式 1.AvailableCluster 顾名思义,就是可用性优先,遍历所有的invokers,选择可用的 ...
- pycharm从本地离线添加模块
豆瓣的源: http://pypi.douban.com/simple pip install matplotlib -i http://pypi.douban.com/simple --truste ...
- group by 和 order by 的区别 + 理解过程
order by 和 group by 的区别order by 和 group by 的区别:1,order by 从英文里理解就是行的排序方式,默认的为升序. order by 后面必须列出排序的字 ...
- react将多个公共组件归成一类,方便调用
目录结构 . ├── component # 公共组件存放 ├ ├── example ├ ├ ├── example1.ts # 例子1 ├ ├ ├── example2.ts # 例子2 ├ ├ ...
- PyCharm-安装&调试
windows安装pycharm 和python的链接: PyCharm:http://www.jetbrains.com/pycharm/ Python:https://www.python.org ...