【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. ...
随机推荐
- kafka和zookeeper安装部署(版本弄不好就是坑)
yum install -y unzip zip 配置host vi /etc/host172.19.68.10 zk1 1. zookeeper zookeeper下载地址 http://mirro ...
- mysql_重置密码
# 修改编码 ```pythonshow variables like '%char%'; #查看当前使用的编码 1.打开配置文件: vim /etc/mysql/my.cnf 2.在[client] ...
- [LOJ2292] [THUSC2016] 成绩单
题目链接 LOJ:https://loj.ac/problem/2292 洛谷:https://www.luogu.org/problemnew/show/P5336 Solution 区间\(\rm ...
- netcore 版本升级 导致的cookie验证失败
排查了两天的问题,本来都是运行正常的cookie验证,突然不好用了,服务器获取不到cookie信息. 我确实是升级了.netcore sdk,之前是2.2.102,后来升级成了2.2.107,一开始并 ...
- C# vb .net实现羽化效果
在.net中,如何简单快捷地实现Photoshop滤镜组中的羽化效果呢?答案是调用SharpImage!专业图像特效滤镜和合成类库.下面开始演示关键代码,您也可以在文末下载全部源码: 设置授权 第一步 ...
- flutter isolate demo
main.dart import 'package:flutter/material.dart'; import 'package:flutter_isolate/flutter_isolate.da ...
- Java 解决Emoji表情过滤问题(转载)
本文作者 我是周洲 原文链接 https://blog.csdn.net/u012904383/article/details/79376707 本人使用的是第三种引入jar的方法 问题: Emoji ...
- IOS模拟器调试ANE
来源:http://www.tuicool.com/articles/AFRJzi 利用iOS模拟器来检测和调试AIR应用程序补充篇 Air3.4来了 除去可以直接往模拟器里面部署应用,还可以往真机里 ...
- php验证码案例
<?php header('Content-type:image/jpeg'); $img=imagecreatetruecolor(120,40); // 背景颜色 $bg_color=ima ...
- 逗号分隔的字符串转成表格参与IN条件查询
返回值为'1,2,3,4,5,6,7',是一个字符串,如果要用IN 查询的话sql认为这是一个完整的字符串,需要将内容分隔转换变成table 定义函数如下: create Function sysfS ...