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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM