一、MongoDB的安装

  MongoDb在windows下的安装与以auth方式启用服务

二、下载驱动

  使用nuget搜索“mongodb”,下载“MongoDB.Driver”(这是官方推荐的一个驱动,完全免费),它会自动下载“MongoDB.Bson”、“MongoDB.Driver.Core”

  

  Api文档地址

 三、代码编写

  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的支持可以让我们更加容易上手查询一些条件难的查询。

Api文档地址该示例源码下载

c#简单操作MongoDB_2.4的更多相关文章

  1. x01.MagicCube: 简单操作

    看最强大脑,发现魔方还是比较好玩的,便买了一个,对照七步还原法,居然也能成功还原. 为什么不写一个魔方程序呢?在网上找了找,略作修改,进行简单操作,还是不错的,其操作代码如下: protected o ...

  2. js简单操作Cookie

    贴一段js简单操作Cookie的代码: //获取指定名称的cookie的值 function getCookie(objName) { var arrStr = document.cookie.spl ...

  3. GitHub学习心得之 简单操作

    作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 前言 本文对Github的基本操作进行了总结, 主要基于以下文章: http://gitre ...

  4. Linq对XML的简单操作

    前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...

  5. Linux 中 Vi 编辑器的简单操作

    Linux 中 Vi 编辑器的简单操作 Vi 编辑器一共有3种模式:命名模式(默认),尾行模式,编辑模式.3种模式彼此需要切换. 一.进入 Vi 编辑器的的命令 vi  filename //打开或新 ...

  6. python(pymysql)之mysql简单操作

    一.mysql简单介绍 说到数据库,我们大多想到的是关系型数据库,比如mysql.oracle.sqlserver等等,这些数据库软件在windows上安装都非常的方便,在Linux上如果要安装数据库 ...

  7. ZooKeeper系列3:ZooKeeper命令、命令行工具及简单操作

    问题导读1.ZooKeeper包含哪些常用命令?2.通过什么命令可以列出服务器 watch 的详细信息?3.ZooKeeper包含哪些操作?4.ZooKeeper如何创建zookeeper? 常用命令 ...

  8. ORACLE的安装与网页版创建表空间的简单操作以及PLsql的简单操作

    1.oracle的安装: 安装简单易学,在这里不做解释.下载看装包后耐心等待,注意安装目录不要有中文字符,尽量按照指定目录进行安装.安装完成后会占用有大约5g的内存. 如果要卸载oracle,需要用其 ...

  9. C#反射技术的简单操作(读取和设置类的属性)

    public class A { public int Property1 { get; set; } } static void Main(){ A aa = new A(); Type type ...

随机推荐

  1. 使用Vue2完成“小红书” app

    小红书项目说明 整体页面格调.功能和原版 app 无限接近.具体页面细节可以下载 “小红书” app查看. 图片素材:https://pan.baidu.com/s/1qYOcx7e 整体要求: · ...

  2. node基础篇二:模块、路由、全局变量课堂(持续)

    今天继续更新node基础篇,今天主要内容是模块.路由和全局变量. 模块这个概念,在很多语言中都有,现在模块开发已经成为了一种潮流,它能够帮助我们节省很多的时间,当然咱们的node自然也不能缺少,看下例 ...

  3. NIO中的易筋经

    匠心零度 转载请注明原创出处,谢谢! 前言 <易筋经>.天下武功出少林,而易筋经是少林寺的镇寺之宝.学好了易筋经就可以轻易地学好其它武功,只不过很少人学到了它的全部精髓.游坦之只是碰巧学了 ...

  4. 欢迎大家走进我的园子 ( ^___^ )y 本博客文章目录整理

    "记录"是见证成长:"成长"则意味着蜕变:“变",创造无限可能! ------致自己 文章越来越多,不容易查看,特整理了一个目录,方便快速查找 坚持的是分享,搬运的是知识,图的是大家的进步,欢迎更多的 ...

  5. Python核心编程--浅拷贝与深拷贝

    一.问题引出浅拷贝 首先看下面代码的执行情况: a = [1, 2, 3] print('a = %s' % a) # a = [1, 2, 3] b = a print('b = %s' % b) ...

  6. jquery通过ajax查询数据动态添加到select

    function addSelectData() { //select的id为selectId //清空select中的数据 $("#selectId").empty(); $.a ...

  7. centos 命令

    1.查看占用端口的进程 netstat -lnp|grep 3000(3000为端口号) Netstat 命令用于显示各种网络相关信息,如网络连接,路由表,接口状态 (Interface Statis ...

  8. 源码中的哲学——通过构建者模式创建SparkSession

    spark2.2在使用的时候使用的是SparkSession,这个SparkSession创建的时候很明显的使用了创建者模式.通过观察源代码,简单的模拟了下,可以当作以后编码风格的参考: 官方使用 i ...

  9. C#学习之设计模式:工厂模式

    最近研究一下设计模式中工厂模式的应用,在此记录如下: 什么是工厂模式? 工厂模式属于设计模式中的创造型设计模式的一种.它的主要作用是协助我们创建对象,为创建对象提供最佳的方式.减少代码中的耦合程度,方 ...

  10. jQuery 核心函数 (十一)

    函数 描述 jQuery() 接受一个字符串,其中包含了用于匹配元素集合的 CSS 选择器. jQuery.noConflict() 运行这个函数将变量 $ 的控制权让渡给第一个实现它的那个库.