c#简单操作MongoDB_2.4
一、MongoDB的安装
MongoDb在windows下的安装与以auth方式启用服务
二、下载驱动
使用nuget搜索“mongodb”,下载“MongoDB.Driver”(这是官方推荐的一个驱动,完全免费),它会自动下载“MongoDB.Bson”、“MongoDB.Driver.Core”
三、代码编写
1、新建四个类:商品、商品销售状态枚举、商品评论、商品评论审核状态枚举
using System.ComponentModel; namespace Models
{
/// <summary>
/// Copyright (C) 2017 yjq 版权所有。
/// 类名:ProductSaleState.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品销售状态
/// 创建标识:yjq 2017/5/21 0:36:02
/// </summary>
public enum ProductSaleState
{
/// <summary>
/// 待审核
/// </summary>
[Description("待审核")]
WaitingCheck = , /// <summary>
/// 上架
/// </summary>
[Description("上架")]
OnSale = , /// <summary>
/// 下架
/// </summary>
[Description("下架")]
OffShelves = , /// <summary>
/// 已销售
/// </summary>
[Description("已销售")]
Saled =
}
} using System.ComponentModel; namespace Models
{
/// <summary>
/// Copyright (C) 2017 yjq 版权所有。
/// 类名:CommentCheckState.cs
/// 类属性:公共类(非静态)
/// 类功能描述:评论审核状态
/// 创建标识:yjq 2017/5/21 0:51:43
/// </summary>
public enum CommentCheckState
{
/// <summary>
/// 待审核
/// </summary>
[Description("待审核")]
WaitingCheck = , /// <summary>
/// 审核通过
/// </summary>
[Description("审核通过")]
Passed = , /// <summary>
/// 审核不通过
/// </summary>
[Description("审核不通过")]
NotPass =
}
} using Infrastructure;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic; namespace Models
{
/// <summary>
/// Copyright (C) 2015 备胎 版权所有。
/// 类名:Product.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品
/// 创建标识:yjq 2017/5/18 14:59:35
/// </summary>
public sealed class Product
{
public Product()
{
} public Product(string name, decimal price) : this()
{
Id = ObjectId.GenerateNewId();
Name = name;
Price = price;
SaleState = ProductSaleState.WaitingCheck;
CreateTime = DateTime.Now;
} /// <summary>
/// 商品ID
/// </summary>
[BsonElement(elementName: "_id")]
public ObjectId Id { get; set; } /// <summary>
/// 商品名字
/// </summary>
public string Name { get; set; } /// <summary>
/// 价格
/// </summary>
public decimal? Price { get; set; } /// <summary>
/// 销售状态
/// </summary>
public ProductSaleState SaleState { get; set; } /// <summary>
/// 添加时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreateTime { get; set; } /// <summary>
/// 修改时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? ModifyTime { get; set; } /// <summary>
/// 商品评论
/// </summary>
public List<ProductComment> Comments { get; set; } public override string ToString()
{
return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
}
}
} using Infrastructure; using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System; namespace Models
{
/// <summary>
/// Copyright (C) 2015 备胎 版权所有。
/// 类名:ProductComment.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品评论
/// 创建标识:yjq 2017/5/18 15:08:32
/// </summary>
public sealed class ProductComment
{
/// <summary>
/// 评论ID
/// </summary>
[BsonElement(elementName: "_id")]
public ObjectId Id { get; set; } /// <summary>
/// 评论内容
/// </summary>
public string Content { get; set; } /// <summary>
/// 评论审核状态
/// </summary>
public CommentCheckState CheckState { get; set; } /// <summary>
/// 添加时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreateTime { get; set; } /// <summary>
/// 修改时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? ModifyTime { get; set; } public override string ToString()
{
return $"评论信息:{Content},审核状态:{CheckState.Desc()}";
}
}
}
商品、商品评论
2、我们先进行新增一个苹果,价格为5.2,且审核状态为待审核的,然后在查询商品列表,输出所有的商品,并显示出其状态
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using Models;
using MongoDB.Bson; namespace MongoDbTest
{
class Program
{
private static string _MongoDbConnectionStr = "mongodb://yjq:123456@localhost:27017/admin"; static void Main(string[] args)
{
var productCollection = GetCollection<Product>();
//添加一个待审核的商品
Product product = new Product("苹果", (decimal)5.20);
productCollection.InsertOne(product);
Console.WriteLine($"添加商品:{product.ToString()}成功。");
var productList = productCollection.Find(new BsonDocument()).ToList();
foreach (var item in productList)
{
Console.WriteLine(item.ToString());
} Console.Read(); } private static IMongoCollection<T> GetCollection<T>(string collectionName = null)
{
MongoUrl mongoUrl = new MongoUrl(_MongoDbConnectionStr);
var mongoClient = new MongoClient(mongoUrl);
var database = mongoClient.GetDatabase(mongoUrl.DatabaseName);
return database.GetCollection<T>(collectionName ?? typeof(T).Name);
}
}
}
运行代码
用robomongodb打开,然后查看对应信息,我们会发现数据库里面存储的时间比我们的当前时间晚8小时,这是因为在安装mongodb的时候,默认的时区不是我们本地的时区导致的,但是只要在时间字段上标记[BsonDateTimeOptions(Kind = DateTimeKind.Local)]就可以在输出的时候显示我们本地时间了。
到这里,我们就完成了简单的新增和查询功能,接下来我们先随机插入几个审核通过、不通过、待审核的商品共100个。
代码如下:
更改product代码
using Infrastructure;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic; namespace Models
{
/// <summary>
/// Copyright (C) 2015 备胎 版权所有。
/// 类名:Product.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品
/// 创建标识:yjq 2017/5/18 14:59:35
/// </summary>
public sealed class Product
{
public Product()
{
} public Product(string name, decimal price) : this(name, price, ProductSaleState.WaitingCheck)
{
} public Product(string name, decimal price, ProductSaleState saleState)
{
Id = ObjectId.GenerateNewId();
Name = name;
Price = price;
SaleState = saleState;
CreateTime = DateTime.Now;
} /// <summary>
/// 商品ID
/// </summary>
[BsonElement(elementName: "_id")]
public ObjectId Id { get; set; } /// <summary>
/// 商品名字
/// </summary>
public string Name { get; set; } /// <summary>
/// 价格
/// </summary>
public decimal? Price { get; set; } /// <summary>
/// 销售状态
/// </summary>
public ProductSaleState SaleState { get; set; } /// <summary>
/// 添加时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreateTime { get; set; } /// <summary>
/// 修改时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? ModifyTime { get; set; } /// <summary>
/// 商品评论
/// </summary>
public List<ProductComment> Comments { get; set; } public override string ToString()
{
return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
}
}
}
Product
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using Models;
using MongoDB.Bson; namespace MongoDbTest
{
class Program
{
private static string _MongoDbConnectionStr = "mongodb://yjq:123456@localhost:27017/admin"; static void Main(string[] args)
{
var productCollection = GetCollection<Product>();
//添加一个待审核的商品
//Product product = new Product("苹果", (decimal)5.20);
//productCollection.InsertOne(product);
//Console.WriteLine($"添加商品:{product.ToString()}成功。"); //批量增加商品
List<Product> productAddList = new List<Product>();
for (int i = ; i < ; i++)
{
productAddList.Add(GetRandomProduct());
}
productCollection.InsertMany(productAddList);
var productList = productCollection.Find(new BsonDocument()).ToList();
foreach (var item in productList)
{
Console.WriteLine(item.ToString());
} Console.Read(); } private static IMongoCollection<T> GetCollection<T>(string collectionName = null)
{
MongoUrl mongoUrl = new MongoUrl(_MongoDbConnectionStr);
var mongoClient = new MongoClient(mongoUrl);
var database = mongoClient.GetDatabase(mongoUrl.DatabaseName);
return database.GetCollection<T>(collectionName ?? typeof(T).Name);
} private static string[] _ProductNames = new string[] { "苹果", "香蕉", "菠萝", "哈密瓜", "西瓜", "黄瓜", "草莓", "桃子", "芒果", "猕猴桃", "梨" };
private static Random rn = new Random();
private static Product GetRandomProduct()
{
var i = rn.Next(_ProductNames.Length);
decimal price = i * ;
var enumValue = rn.Next(, );
return new Product(_ProductNames[i], price, (ProductSaleState)enumValue);
}
}
}
Program
然后运行,可以去robo查看结果,发现数据库里面总共有101条数据
批量增加的操作也执行了,那么接下来我们就继续执行分页和修改删除的功能。
首先我们先查询返回总记录数和前20条商品信息的内容:
static void Main(string[] args)
{
var productCollection = GetCollection<Product>();
//添加一个待审核的商品
//Product product = new Product("苹果", (decimal)5.20);
//productCollection.InsertOne(product);
//Console.WriteLine($"添加商品:{product.ToString()}成功。"); //批量增加商品
//List<Product> productAddList = new List<Product>();
//for (int i = 0; i < 100; i++)
//{
// productAddList.Add(GetRandomProduct());
//}
//productCollection.InsertMany(productAddList);
//var productList = productCollection.Find(new BsonDocument()).ToList();
//foreach (var item in productList)
//{
// Console.WriteLine(item.ToString());
//}
FilterDefinition<Product> filter = new BsonDocument();
long productAllCount = productCollection.Count(filter);
var productList = productCollection.Find(filter).Skip().Limit().ToList();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"总记录数为{productAllCount.ToString()}");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("前20条商品信息为:");
Console.ForegroundColor = ConsoleColor.White;
foreach (var item in productList)
{
Console.WriteLine(item.ToString());
}
Console.Read(); }
Program
因为商品是随机产生的,所以可能导致你我之间的结果不一样。
接下来我们查询待审核的商品,并显示待审核的商品总数,我们更改下filte(使用lambda表达式树比较方便),二选一都可以
Expression<Func<Product, bool>> expression = m => m.SaleState == ProductSaleState.WaitingCheck;
long productAllCount = productCollection.Count(expression);
var productList = productCollection.Find(expression).Skip().Limit().ToList();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"总记录数为{productAllCount.ToString()}");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("前20条商品信息为:");
Console.ForegroundColor = ConsoleColor.White;
foreach (var item in productList)
{
Console.WriteLine(item.ToString());
}
待审核商品
#region 待审核 filter构建
var filter = Builders<Product>.Filter.Eq("SaleState", ProductSaleState.WaitingCheck);
long productAllCount = productCollection.Count(filter);
var productList = productCollection.Find(filter).Skip().Limit().ToList();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"总记录数为{productAllCount.ToString()}");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("前20条商品信息为:");
Console.ForegroundColor = ConsoleColor.White;
foreach (var item in productList)
{
Console.WriteLine(item.ToString());
}
#endregion
filter 构建条件
接下来我们对第1条待审核的商品进行审核通过的操作,并增加一条“哇,这个好好吃啊!”的评论。
using Infrastructure;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic; namespace Models
{
/// <summary>
/// Copyright (C) 2015 备胎 版权所有。
/// 类名:Product.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品
/// 创建标识:yjq 2017/5/18 14:59:35
/// </summary>
public sealed class Product
{
public Product()
{
} public Product(string name, decimal price) : this(name, price, ProductSaleState.WaitingCheck)
{
} public Product(string name, decimal price, ProductSaleState saleState)
{
Id = ObjectId.GenerateNewId();
Name = name;
Price = price;
SaleState = saleState;
CreateTime = DateTime.Now;
} /// <summary>
/// 商品ID
/// </summary>
[BsonElement(elementName: "_id")]
public ObjectId Id { get; set; } /// <summary>
/// 商品名字
/// </summary>
public string Name { get; set; } /// <summary>
/// 价格
/// </summary>
public decimal? Price { get; set; } /// <summary>
/// 销售状态
/// </summary>
public ProductSaleState SaleState { get; set; } /// <summary>
/// 添加时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreateTime { get; set; } /// <summary>
/// 修改时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? ModifyTime { get; set; } /// <summary>
/// 商品评论
/// </summary>
public List<ProductComment> Comments { get; set; } public override string ToString()
{
return $"{Id}:{Name},价格{Price}元,审核状态{SaleState.Desc()}";
} public void ShowComments()
{
if (Comments != null)
{
foreach (var item in Comments)
{
Console.WriteLine(item.ToString());
}
} } public void Comment(string content)
{
if (Comments == null)
{
Comments = new List<Models.ProductComment>();
}
Comments.Add(new Models.ProductComment(content));
}
}
}
Product类的更改
using Infrastructure; using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System; namespace Models
{
/// <summary>
/// Copyright (C) 2015 备胎 版权所有。
/// 类名:ProductComment.cs
/// 类属性:公共类(非静态)
/// 类功能描述:商品评论
/// 创建标识:yjq 2017/5/18 15:08:32
/// </summary>
public sealed class ProductComment
{
public ProductComment(string content)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
Id = ObjectId.GenerateNewId();
Content = content;
CheckState = CommentCheckState.WaitingCheck;
CreateTime = DateTime.Now;
} /// <summary>
/// 评论ID
/// </summary>
[BsonElement(elementName: "_id")]
public ObjectId Id { get; set; } /// <summary>
/// 评论内容
/// </summary>
public string Content { get; set; } /// <summary>
/// 评论审核状态
/// </summary>
public CommentCheckState CheckState { get; set; } /// <summary>
/// 添加时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreateTime { get; set; } /// <summary>
/// 修改时间
/// </summary>
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? ModifyTime { get; set; } public override string ToString()
{
return $"评论信息:{Content},审核状态:{CheckState.Desc()}";
}
}
}
ProductComment类代码的更改
var beforeUpdateProduct = productCollection.Find(m => m.SaleState == ProductSaleState.WaitingCheck).FirstOrDefault();
Console.WriteLine($"更新前信息{beforeUpdateProduct?.ToString()}");
//注意线程安全,这里只是做演示
beforeUpdateProduct.Comment("哇,这个好好吃啊!");
var updateFilter = Builders<Product>.Update.Set(m => m.SaleState, ProductSaleState.OnSale).Set(m => m.ModifyTime, DateTime.Now).Set(m => m.Comments, beforeUpdateProduct.Comments);
var updateResult = productCollection.UpdateOne(m => m.Id == beforeUpdateProduct.Id, updateFilter);
if (updateResult.IsModifiedCountAvailable)
{
var afterUpdateProduct = productCollection.Find(m => m.Id == beforeUpdateProduct.Id).FirstOrDefault();
Console.WriteLine("更新销售状态成功=====");
Console.WriteLine($"更新后信息{afterUpdateProduct?.ToString()}");
Console.WriteLine("评论信息:");
afterUpdateProduct.ShowComments();
}
else
{
Console.WriteLine("更新失败=====");
}
更新审核状态,并添加评论
下一步我们查找有评论待审核的商品列表
var commentWaitingCheckProducts = productCollection.Find(m => m.Comments.Where(k => k.CheckState == CommentCheckState.WaitingCheck).Any()).ToEnumerable();
foreach (var item in commentWaitingCheckProducts)
{
Console.WriteLine(item.ToString());
}
查询评论有待审核的商品
var projection = Builders<Product>.Projection.Expression(m => new ProductDto
{
Comments = m.Comments,
Id = m.Id,
Name = m.Name,
Price = m.Price,
SaleState = m.SaleState
}); var commentWaitingCheckProducts = productCollection.Find(m => m.Comments.Where(k => k.CheckState == CommentCheckState.WaitingCheck).Any()).Project(projection).ToEnumerable();
foreach (var item in commentWaitingCheckProducts)
{
Console.WriteLine(item.ToString());
}
利用Projection查询dto
简单的操作就到这里了,其它的一些操作可以根据文档来,驱动对lambda的支持可以让我们更加容易上手查询一些条件难的查询。
c#简单操作MongoDB_2.4的更多相关文章
- x01.MagicCube: 简单操作
看最强大脑,发现魔方还是比较好玩的,便买了一个,对照七步还原法,居然也能成功还原. 为什么不写一个魔方程序呢?在网上找了找,略作修改,进行简单操作,还是不错的,其操作代码如下: protected o ...
- js简单操作Cookie
贴一段js简单操作Cookie的代码: //获取指定名称的cookie的值 function getCookie(objName) { var arrStr = document.cookie.spl ...
- GitHub学习心得之 简单操作
作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 前言 本文对Github的基本操作进行了总结, 主要基于以下文章: http://gitre ...
- Linq对XML的简单操作
前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...
- Linux 中 Vi 编辑器的简单操作
Linux 中 Vi 编辑器的简单操作 Vi 编辑器一共有3种模式:命名模式(默认),尾行模式,编辑模式.3种模式彼此需要切换. 一.进入 Vi 编辑器的的命令 vi filename //打开或新 ...
- python(pymysql)之mysql简单操作
一.mysql简单介绍 说到数据库,我们大多想到的是关系型数据库,比如mysql.oracle.sqlserver等等,这些数据库软件在windows上安装都非常的方便,在Linux上如果要安装数据库 ...
- ZooKeeper系列3:ZooKeeper命令、命令行工具及简单操作
问题导读1.ZooKeeper包含哪些常用命令?2.通过什么命令可以列出服务器 watch 的详细信息?3.ZooKeeper包含哪些操作?4.ZooKeeper如何创建zookeeper? 常用命令 ...
- ORACLE的安装与网页版创建表空间的简单操作以及PLsql的简单操作
1.oracle的安装: 安装简单易学,在这里不做解释.下载看装包后耐心等待,注意安装目录不要有中文字符,尽量按照指定目录进行安装.安装完成后会占用有大约5g的内存. 如果要卸载oracle,需要用其 ...
- C#反射技术的简单操作(读取和设置类的属性)
public class A { public int Property1 { get; set; } } static void Main(){ A aa = new A(); Type type ...
随机推荐
- 树形dp系列
1.火车站开饭店 最大独立集裸题 #include<iostream> #include<cstdio> #include<cstdlib> #include< ...
- volatile作用及相关集合类
在工作一年多之后,java程序员都会了解到volatile 这个修饰符, 其在多线程环境下解决了long/double写操作的原子性.基本变量的可见性.通过建立内存屏障保证指令有序性 那么在哪些Jav ...
- 第四章初始CSS3预习笔记
第四章 初始CSS3预习笔记 一: 1: 什么是CSS? 全称是层叠样式表;/通常又称为风格样式表,.他是用来进行网页风格设计的; 2:CSS的优势: 1>内容以表现分离,即使用u前面学习的HT ...
- SQLServer:无法生成 SSPI 上下文(Cannot generate SSPI context)
服务器版本:windows Server 2012 R2 数据库版本: SQLServer 2016 +sp1 SQL2016AlwaysOn群集: 由于重启过域控,造成后续的部分服务器也解析不到DN ...
- Mac新手从入门到放弃MongoDB
1. 简介 MongoDB 是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最 ...
- HTML知识点总结之img、scirpt、link标签
<img>元素 使用<img>可以在网页插入一个图片,但实际上<img>标签并不会在网页中直接插入图像,而是从网页上链接图像. <img>的主要属性 ( ...
- Android数据库之判断表是否存在
Android开发的时候我们可能会用到它的本地数据库,在使用的时候有可能我们已经储存了数据了,但是,我们的表已经创建了,里面有数据,我们要怎么判断表是否已经创建可能就需要琢磨一下. 以下便是利用了,查 ...
- 记一个http-proxy-middleware 代理访问nginx映射的接口不通过的问题(connection close)
工作过程中遇见一个问题,使用Vue-cli 搭建了一个工程,由于跨域的问题 使用了自带的dev-server Express Server(A后台) http-proxy-middleware 去访问 ...
- ps 替换背景以及调整尺寸
领导吩咐我修改她的图片背景,尺寸, 屁颠屁颠去弄,半小时后发现大学里学的 ps 忘差不多了,这里总结一下修改图片背景以及尺寸的基本操作. 1. 去除原背景 方法一: 选中魔术橡皮擦, 点击原图中背景, ...
- HashTable源码阅读
环境jdk1.8.0_121 与HashMap有几点区别 在HashMap中,冲突的值会在bucket形成链表,当达到8个,会形成红黑树,而在HashTable中,冲突的值就以链表的形式存储 publ ...