一、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部分做了相应的修改。

    MongoClient被设计成线程安全、可以被多线程共享的。通常访问数据库集群的应用只需要一个实例,所以这次调整我们设计成单例形式。如果出于某些原因,你决定使用多个实例,请注意:所有资源使用限制(最大连接数等等)对每个MongoClient都适用;销毁一个实例时,请确认调用MongoClient.close()方法来清理资源。

设置配置信息

//连接地址
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:

  1. 使用 BsonDocument 模型
  2. 使用自定义的实体模型

如果我们的文档结构比较复杂,或者定义为实体模型比较困难,那么推荐使用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);
}

参考:使用c#对MongoDB进行查询(1)

 

【MongoDB】在C#中使用的更多相关文章

  1. (转载)MongoDB C#驱动中Query几个方法

    MongoDB C#驱动中Query几个方法 Query.All("name", "a", "b");//通过多个元素来匹配数组 Query ...

  2. 处理范例代码Webapi中的Mongodb的Bson中ObjectId反序列化异常

    微软代码范例中的一个Bug 处理Mongodb的Bson中ObjectId反序列化异常 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/f ...

  3. MongoDB数据库设计中6条重要的经验法则

    Part 1 原文:6 Rules of Thumb for MongoDB Schema Design: Part 1 By William Zola, Lead Technical Support ...

  4. MongoDB 在Node中的应用

    转: MongoDB 在Node中的应用 文章目录 一 .什么是 MongoDB? 二.小Demo 三.Demo 增删改查 3.1 新增 3.2 查询 3.2.1 查询所有 [{},{}] 找不到返回 ...

  5. NoSql非关系型数据库之MongoDB应用(三):MongoDB在项目中的初步应用

    业精于勤,荒于嬉:行成于思,毁于随. 我们可以结合相关的IDE做一个简单的增删改查了,实现MongoDB在项目中的初步应用. 前提是安装了MongoDB服务和MongoDB可视化工具,没有安装的可以点 ...

  6. 利用log4j+mongodb实现分布式系统中日志统一管理

    背景     在分布式系统当中,我们有各种各样的WebService,这些服务可能分别部署在不同的服务器上,并且有各自的日志输出.为了方便对这些日志进行统一管理和分析.我们可以将日志统一输出到指定的数 ...

  7. mongodb在java中的查询

    mongodb 根据_id 查询记录: public Price queryPriceById(String id) throws Exception { return mongoTemplate.f ...

  8. MongoDb Replica Set中使用的地址

    Unable to connect to a member of the replica set matching the read preference Primary 今天尝试使用MongoDB ...

  9. 从MongoDB的ObjectId中获取时间信息

    MongoDB默认使用_id字段作为主键,类型为ObjectId.ObjectId的生成有一定的规则,详情可以查看这篇文章 - MongoDB深究之ObjectId.如果你在写入数据库的时候忘记写入创 ...

  10. MongoDB使用过程中的一些问题

    1.MongoDB配置修改不生效的问题:今天因为某个原因,需要修改mongodb的配置文件. 改完以后,在init.d里面restart命令重启server,后来stop又start重启server. ...

随机推荐

  1. 【LEETCODE】35、169题, Majority Element

    package y2019.Algorithm.array; import java.util.HashMap; import java.util.Map; /** * @ProjectName: c ...

  2. C# 值类型和引用类型等值判断

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. Socket HttpListen

    HttpListener sSocket = new HttpListener(); sSocket.Prefixes.Add("http://127.0.0.1:8080/"); ...

  4. 管道模型(Pipeline)

    1.使用make_blobs来生成数据集,然后对数据集进行预处理 #导入数据集生成器 from sklearn.datasets import make_blobs #导入数据集拆分工具 from s ...

  5. Coldfusion Sql查询分组输出

    <cfoutput query="myQry" group="date"> #date# <cfoutput> #detail# < ...

  6. 微信小程序实现下拉刷新上拉加载

    代码片段:https://developers.weixin.qq.com/s/K9VbWZmy7e8C

  7. Arm存储器

    Arm可以引出27根地址线,只能实现128MB的寻址,那么要如何实现1GB的寻址呢?答案就是使用nGCS片选线,nGCSx为低电平为选中相应的外接设备.一共八根片选线,也就是bank1,bank2-以 ...

  8. centos7开启80端口及其他端口

    首先centos7的防火墙由iptables改为了firewalld 1. 执行命令:firewall-cmd --zone=public --add-port=80/tcp  --permanent ...

  9. spark 机器学习 随机森林 实现(二)

    通过天气,温度,风速3个特征,建立随机森林,判断特征的优先级结果 天气 温度 风速结果(0否,1是)天气(0晴天,1阴天,2下雨)温度(0热,1舒适,2冷)风速(0没风,1微风,2大风)1 1:0 2 ...

  10. urllib模块中parse函数中的urlencode和quote_plus方法

    本来只是向看一下quote_plus的作用,然后发现urlencode方法也是很方便的一个组合字符串的方法首先是介绍一下urlencode,他是将一些传入的元素使用&串联起来,效果如下: &g ...