c#简单操作MongoDB_2.4

一、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 = 1,

        /// <summary>
        /// 上架
        /// </summary>
        [Description("上架")]
        OnSale = 2,

        /// <summary>
        /// 下架
        /// </summary>
        [Description("下架")]
        OffShelves = 3,

        /// <summary>
        /// 已销售
        /// </summary>
        [Description("已销售")]
        Saled = 4
    }
}

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 = 1,

        /// <summary>
        /// 审核通过
        /// </summary>
        [Description("审核通过")]
        Passed = 2,

        /// <summary>
        /// 审核不通过
        /// </summary>
        [Description("审核不通过")]
        NotPass = 3
    }
}

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:[email protected]: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:[email protected]: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 = 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());
            }

            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 * 15;
            var enumValue = rn.Next(1, 5);
            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(0).Limit(20).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(0).Limit(20).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(0).Limit(20).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文档地址该示例源码下载

时间: 2024-08-25 17:29:04

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

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

1.oracle的安装: 安装简单易学,在这里不做解释.下载看装包后耐心等待,注意安装目录不要有中文字符,尽量按照指定目录进行安装.安装完成后会占用有大约5g的内存. 如果要卸载oracle,需要用其自带的卸载工具进行卸载[universal installer],然后删除注册表项,删除环境变量,删除目录并且重新启动计算机. 2.在网页版进行创建表空间: 进入网页版: 在电脑的服务中我们可以看到一共有7个oracle的服务项目,其中只有三个是正在启动中.这三项中,只有当OracleDBConso

简单操作只需10秒破解PDF加密文件

简单操作只需10秒破解PDF加密文件 [尊重原创,转载请注明出处]http://blog.csdn.net/guyuealian/article/details/51345950 如何破解PDF加密文件,如何破解PDF密码呢,破解加密的PDF文件? 从网上下载的PDF文件,由于版权的问题,作者经常会加密禁止读者复制修改等权限,如下面的PDF文档,用Adobe pdf Reader打开时,会显示"已加密"的字样,虽然可以阅读,但不能修改和标记. 为了解决这个问题,可以采用绕过破解密码这一

C++ 文件的简单操作

=================================================================== 编写程序时,很多时候都要对文件进行操作,比如从文件中读取数据,通过程序将一些数据保存到文件中等等.. 以下是c++对文件的一些简单操作. =================================================================== 一.文件输出 要将程序中的数据输出到文件中,一般需要以下5个步骤: ① 包含fstream

mysql数据库很简单操作

进入linux系统 root   >/usr/bin/mysql -u root mysql>show databases;                    #查看数据库 mysql>use  testtable;                        #testtable 为所要查看的库,应用数据库 mysql>show tables;                          #查看所有表 mysql>desc abc_table          

ftp简单操作及解说

一.实验拓扑 服务器 ------------------------客户机 二.实验条件 试验机在同一个网段,可以互相ping通. 确定装在了ftp软件包. 三.实验一: 匿名用户与本地用户都可以登录 匿名用户登录到/var/ftp,只能下载不能上传 本地用户登录到本地用户的家目录,可以上传和下载 实验步骤; [[email protected] ~]# rpm -q vsftp              //检测是否安装软件 package vsftp is not installed   

nfs简单操作及解说

NFS的实验报告 一.实验拓扑: 服务器 ----------      客户机 二.实验条件: 服务器的ip:192.168.4.5/24 客户机的ip:192.168.4.200 要确定机器有安装nfs包跟RPC软件包. 三.实验要求: 将/root 共享给192.168.4.200 可写,同步,允许客户机以root权限访问 NFS 服务端操作: 修改配置: [[email protected] ~]# vim /etc/exports    //修改配置的地址 [[email protec

PgSQL简单操作

********************************************** *基本操作 ********************************************** 数据库操作 $ psql test $ psql -h localhost -U username -W newpwd -p 5432 test =# create database mail_db; =# create database mail_db owner sunny; =# drop d

JS的简单操作和表单以及事件

HTML:主要用于往页面上放置所需要的控件. CSS:主要用来控制页面以及上面控件的样式. JS:主要用来控制页面上的特效以及数据交互. JS也分为顺序,条件(IF()... ELSE()),循环(FOR())三种语句,与C#基本一致. JS定义变量统一用var,定义数组不固定长度和类型,类似C#中的集合. JS的简单操作: DOM操作: 一.window: 1.window.onload 页面打开完再执行后面的操作 2.window.open(1,2,3,4) - 打开新页面, 1 - 打开页

Java时间简单操作

使用java操作时间感觉真真蛋疼,还是我大C#舒服,一个DateTime全部搞定 这里的Date指的是java.util.Date 获取当前时间: // 创建一个当前时间的Date对象 Date time = new Date(); 蛋疼的地方,对时间增.减操作: // 使用Calendar类对时间增.减操作 Calendar c = Calendar.getInstance();// 获得一个Calendar实例,该类是抽象类所以不可以使用new构造方法 // 使用setTime方法创建一个时