c#簡單操做MongoDB_2.4

1、MongoDB的安裝html

  MongoDb在windows下的安裝與以auth方式啓用服務git

2、下載驅動github

  使用nuget搜索「mongodb」,下載「MongoDB.Driver」(這是官方推薦的一個驅動,徹底免費),它會自動下載「MongoDB.Bson」、「MongoDB.Driver.Core」mongodb

  

  Api文檔地址數據庫

 3、代碼編寫express

  一、新建四個類:商品、商品銷售狀態枚舉、商品評論、商品評論審覈狀態枚舉windows

  
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()}";
        }
    }
}
商品、商品評論

  二、咱們先進行新增一個蘋果,價格爲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)]就能夠在輸出的時候顯示咱們本地時間了。dom

  

 

 

到這裏,咱們就完成了簡單的新增和查詢功能,接下來咱們先隨機插入幾個審覈經過、不經過、待審覈的商品共100個。ide

代碼以下:

 更改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 = 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文檔地址該示例源碼下載

相關文章
相關標籤/搜索