MongoDB.Driver 2.4以上版本 在.NET中的基本操作
MongoDB.Driver是操作mongo数据库的驱动,最近2.0以下版本已经从GitHub和Nuget中移除了,也就是说.NET Framework4.0不再能从官方获取到MongoDB的驱动了,其次MongoDB.Driver2.0开始API变更巨大,本文不适用MongoDB.Driver2.0以下版本,亦不适用.NET Framework4.5以下版本
要在.NET中使用MongoDB,就必须引用MongoDB的驱动,使用Nuget安装MongoDB.Driver是最方便的,目前Nuget支持的MongoDB程序包有对.NET Framework4.5以上版本的依赖
安装完成之后会在引用中新增三个MongoDB的程序集引用,其中MongoDB.Driver.Core在2.0版本以下是没有的

先构建一个实体基类,因为Mongo要求每个文档都有唯一Id,默认为ObjectId类型(根据时间Mac地址Pid算出来的,类似GUID,适用于分布式),在这个基类中添加Id属性
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
/// <summary>
/// 自定义类型Id
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseEntity<T>
{
public T Id { get; set; }
}
/// <summary>
/// Mongo默认填充ObjectId类型的Id
/// </summary>
public abstract class DefaultIdEntity : BaseEntity<ObjectId>
{
}
}
开始构建数据库访问类DbContext
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
public class DbContext
{
public readonly IMongoDatabase _db;
public DbContext()
{
//此为开启验证模式 必需使用用户名 密码 及指定登陆的数据库 可采用,分割连接多个数据库
var client = new MongoClient("mongodb://root:123456@192.168.20.54:27017/admin");
//未开启验证模式数据库连接
// var client = new MongoClient("mongodb://127.0.0.1:27017");
//指定要操作的数据库
_db = client.GetDatabase("mytest");
} private static string InferCollectionNameFrom<T>()
{
var type = typeof(T);
return type.Name;
} public IMongoCollection<T> Collection<T, TId>() where T : BaseEntity<TId>
{
var collectionName = InferCollectionNameFrom<T>();
return _db.GetCollection<T>(collectionName);
}
/// <summary>
/// 实体类名和数据库中文档(关系型数据库中的表)名一致时使用
/// </summary>
public IMongoCollection<T> Collection<T>() where T : DefaultIdEntity
{
var collectionName = InferCollectionNameFrom<T>();
return _db.GetCollection<T>(collectionName);
} public IMongoCollection<T> Collection<T, TId>(string collectionName) where T : BaseEntity<TId>
{
return _db.GetCollection<T>(collectionName);
}
/// <summary>
/// 实体类名和数据库中文档(关系型数据库中的表)不一致时使用,通过collectionName指定要操作得文档
/// </summary>
public IMongoCollection<T> Collection<T>(string collectionName) where T : DefaultIdEntity
{
return _db.GetCollection<T>(collectionName);
}
}
}
现有数据库数据 文档book 包含数据如下

开始构建与文档对应的实体,mongo是文档数据库,对单词得大小写是敏感得,所以构建的实体的字段也应该是小写的,有点不符合习惯
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
public class book : DefaultIdEntity
{
public string title { get; set; }
public double price { get; set; }
public string author { get; set; }
public string publisher { get; set; }
public int saleCount { get; set; }
}
}
现在开始增删查改操作,其中查找和删除的filter参数有两种形式,lambda和Definition
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
public class OperatDb
{
static IMongoCollection<book> bookDao;
static OperatDb()
{
bookDao = new DbContext().Collection<book>();
} public static void Excute()
{
Console.WriteLine();
QueryAll();
Console.WriteLine();
Query();
Console.WriteLine();
Insert();
Console.WriteLine();
QueryAll();
Console.WriteLine();
Update();
Console.WriteLine();
Delete();
Console.WriteLine();
QueryAll();
Console.ReadKey();
}
public static void QueryAll()
{
var books = bookDao.Find(x => true).ToList();
foreach (var item in books)
{
Console.WriteLine(item.ToString());
}
} public static void Query(System.Linq.Expressions.Expression<Func<book, bool>> filter = null)
{
if (filter == null) filter = x => x.author == "韩寒";
var books = bookDao.Find(filter).ToList();
foreach (var item in books)
{
Console.WriteLine(item.ToString());
}
} public static void Update()
{
var filter = Builders<book>.Filter.Eq(x => x.title, "悲伤逆流成河");
var book = bookDao.Find(filter).FirstOrDefault();
Console.WriteLine("更新前:{0}", book.ToString());
var update = Builders<book>.Update.Set(x => x.publisher, "新时代出版社")
.Set(x => x.price, )
.Inc(x => x.saleCount, );
var result = bookDao.UpdateOne(filter, update);
Console.WriteLine("IsAcknowledged:{0} MatchedCount:{1} UpsertedId:{2} IsModifiedCountAvailable:{3} ModifiedCount:{4}",
result.IsAcknowledged, result.MatchedCount, result.UpsertedId, result.IsModifiedCountAvailable, result.ModifiedCount);
book = bookDao.Find(filter).FirstOrDefault();
Console.WriteLine("更新后:{0}", book.ToString());
} public static void Delete()
{
var result = bookDao.DeleteOne(x => x.title == "悲伤逆流成河");
Console.WriteLine("DeletedCount:{0} IsAcknowledged:{1} ", result.DeletedCount, result.IsAcknowledged);
} public static void Insert()
{
var bookInfo = new book
{
Id = new MongoDB.Bson.ObjectId(),
author = "郭敬明",
price = 10.00,
publisher = "春风文艺出版社",
saleCount = ,
title = "悲伤逆流成河"
};
bookDao.InsertOne(bookInfo);
}
}
}
因为我对book类的ToString方法进行了重写,所以输出结果如下

上面都是用的数据库和实体字段名一致的情况,如果不一致怎么办呢,Xml和Json等序列化都有标签特性可以用别名,Bson肯定也会有,新建BookInfo实体如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
public class BookInfo : DefaultIdEntity
{
public string Title { get; set; }
public double Price { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public int SaleCount { get; set; }
}
}
将上面执行操作的book全部替换成BookInfo试试,发现没报错,再去数据库看看会发现,数据库新增了一个文档,我们预期得结果是要操作在book上,显然这不是我们想要的

现在将调用Collection调用改为指定collectionName为book的形式
static IMongoCollection<BookInfo> bookDao;
static OperatDb()
{
bookDao = new DbContext().Collection<BookInfo>("book");
}
再次运行程序,发现报错了,文档节点和实体字段不匹配

现在给BookInfo的字段都加上Bson的标签特性
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MongoTest
{
public class BookInfo : DefaultIdEntity
{
[BsonElement("title")]
public string Title { get; set; }
[BsonElement("price")]
public double Price { get; set; }
[BsonElement("author")]
public string Author { get; set; }
[BsonElement("publisher")]
public string Publisher { get; set; }
[BsonElement("saleCount")]
public int SaleCount { get; set; }
}
}
现在一切正常了,显示结果和之前的一样就不再贴图了,有子文档的数据操作与此类似,譬如有如下数据

构建实体如下
public class Director : Entity
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("country")]
public string Country { get; set; }
[BsonElement("age")]
public int Age { get; set; }
[BsonElement("movies")]
public List<Movie> Movies { get; set; }
}
public class Movie
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("year")]
public int Year { get; set; }
}
MongoDB.Driver 2.4以上版本 在.NET中的基本操作的更多相关文章
- 在.net下打造mongoDb基于官方驱动最新版本
还是一如既往先把结构图放出来,上上个版本添加了redis的缓存,但是不满足我的需求,因为公司有项目要求是分布式所以呢,这里我就增加了mongoDb进行缓存分布式,好了先看结构图. 总的来说比较蛋疼,因 ...
- c# MongoDB Driver 官方教程翻译
先贴官方文档地址:http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/ 安装部分很简单,nuget搜 ...
- MongoDB Driver 简单的CURD
c#中我们可以使用MongoDB.Driver驱动进行对MongoDB数据库的增删改查. 首先需要在NuGet中安装驱动 安装完毕后会发现会有三个引用 其中 MongoDB.Driver和MongoD ...
- 基于MongoDB.Driver的扩展
由于MongoDB.Driver中的Find方法也支持表达式写法,结合[通用查询设计思想]这篇文章中的查询思想,个人基于MongoDB扩展了一些常用的方法. 首先我们从常用的查询开始,由于MongoD ...
- MongoDB系列:五、MongoDB Driver使用正确的姿势连接复制集
MongoDB复制集(Replica Set)通过存储多份数据副本来保证数据的高可靠,通过自动的主备切换机制来保证服务的高可用.但需要注意的时,连接副本集的姿势如果不对,服务高可用将不复存在. 使用复 ...
- C# mongoDB Driver 使用对象方式查询语法大全
#region 查询方法 /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T" ...
- php MongoDB driver 查询实例
//是否只查mx $mx_on_switch = I("post.mx_on_switch"); //mx模糊查询 $mx_vague_check = I("post.m ...
- PHP7 - MongoDB Driver 使用心得
php7 只能使用Mongodb driver来驱动mongodb. 使用Mongodb Driver连接数据库 刚开始使用Mongodb Driver的时候我是拒绝的.查看官方文档只看到一排的类和不 ...
- MongoDB入门及 c# .netcore客户端MongoDB.Driver使用
MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系 ...
随机推荐
- MySQL · 引擎特性 · InnoDB redo log漫游(转)
前言 InnoDB 有两块非常重要的日志,一个是undo log,另外一个是redo log,前者用来保证事务的原子性以及InnoDB的MVCC,后者用来保证事务的持久性. 和大多数关系型数据库一样, ...
- 奇异值与主成分分析(PCA)
主成分分析在上一节里面也讲了一些,这里主要谈谈如何用SVD去解PCA的问题.PCA的问题其实是一个基的变换,使得变换后的数据有着最大的方差.方差的大小描述的是一个变量的信息量,我们在讲一个东西的稳定性 ...
- Charles 抓包工具的使用
抓包工具有很多,目前用过的有Charles, Fiddler, burpsuite.下面主要是Charles 的应用实例. 一. 用Charles抓包 1. PC 抓包 打开Charles, 确保“录 ...
- 微信小程序组件action-sheet
操作反馈action-sheet:官方文档 Demo Code: Page({ data: { actionSheetHidden: true, actionSheetItems: ['item1', ...
- hdu2609 How many
地址:http://acm.hdu.edu.cn/showproblem.php?pid=2609 题目: How many Time Limit: 2000/1000 MS (Java/Others ...
- Pyspark访问Hbase
作者:Syn良子 出处:http://www.cnblogs.com/cssdongl/p/7347167.html 转载请注明出处 记录自己最近抽空折腾虚拟机环境时用spark2.0的pyspark ...
- Ubuntu16.04桌面版 连接到ftp服务器
Ftp服务器在不同的网段,需要临时添加网段 不同网段临时添加方法: root@xzrs:/home/rxf# ip addr add 10.1.2.127/24 dev enp0s25 电脑左侧“连接 ...
- Centos编译安装 LAMP (apache-2.4.7 + mysql-5.5.35 + php 5.5.8)+ Redis
转载地址:http://www.cnblogs.com/whoamme/p/3530056.html 软件源代码包存放位置:/usr/local/src 源码包编译安装位置:/usr/local/软件 ...
- 在LAMP的生产环境内添加PHP的cURL扩展模块
服务器运行一段时间后,可能突然会需求添加某个扩展,如curl.pdo.xmlrpc等, 这就需要在不重新编译 PHP 的情况下独立添加扩展. 下面以安装curl为例,介绍具体安装步骤. 1.安装c ...
- Python面试题之Python生成器
首先说明一下生成器也是迭代器,也有迭代器的那些优点. 那为什么要生成器呢?因为到目前为止都 不是你写的迭代器,都是别人定义好的.那如何自己去造一个迭代器呢?下面的内容就会给你答案. 想要自己造一个迭代 ...