技术思绪摘录旅行笔记
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。在高负载的情况下,添加更多的节点,可以保证服务器性能。MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

你可以在mongodb官网下载该安装包,地址为:https://www.mongodb.com/download-center#community

MonggoDB支持以下平台:

  • OS X 32-bit

  • OS X 64-bit

  • Linux 32-bit

  • Linux 64-bit

  • Windows 32-bit

  • Windows 64-bit

  • Solaris i86pc

  • Solaris 64

我们下载社区版本就行了

安装之后,在我们系统的服务中,会增加一个 MongoDB Server (MongoDB) 名称的服务

image.png

说明已经安装好了

基本操作

>use DATABASE_NAME //如果数据库不存在,则创建数据库,否则切换到指定数据库。
创建之后  查询所有数据库,不会显示,是因为没有数据,只要有一条数据,则会显示出来

>show dbs //显示所有数据库

>show collections //显示当前数据库下的所有集合

>db.runoob.insert({"name":"菜鸟教程","taxcode":"123456"}) //添加数据

> db.runoob.update({'name':'菜鸟教程'},{'$set':{'taxcode':'test'}},upsert=true,multi=false) //name为菜鸟教程 更新记录taxcode为test

>db.runoob.find() //查询数据

> db.runoob.remove() //删除所有数据

> db.runoob.remove({'name':'菜鸟教程'}) //删除记录name为菜鸟教程

>db.dropDatabase() //删除当前数据库


接下来说下如何在.NET 项目中使用MongoDb

1、创建一个项目MongoDbDemo

image.png

2、添加引用,一个驱动,一个json序列化相关

image.png

3、写代码

封装ContextDb.cs 数据库连接

using MongoDB.Driver;

namespace MongoDbDemo.MongoDb
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public class ContextDb
    {
        /// <summary>
        /// 数据库连接
        /// </summary>
        private static readonly string connStr = "mongodb://127.0.0.1:27017";//GlobalConfig.Settings["mongoConnStr"];

        /// <summary>
        /// 操作的数据库
        /// </summary>
        private static readonly string dbName = "demo1";//GlobalConfig.Settings["mongoDbName"];

        /// <summary>
        /// The database
        /// </summary>
        private static IMongoDatabase db = null;

        /// <summary>
        /// The lock helper
        /// </summary>
        private static readonly object lockHelper = new object();

        /// <summary>
        /// Prevents a default instance of the <see cref="ContextDb"/> class from being created.
        /// </summary>
        private ContextDb() { }

        /// <summary>
        /// 获取一个数据库对象
        /// </summary>
        /// <returns></returns>
        public static IMongoDatabase GetDb()
        {
            if (db == null)
            {
                lock (lockHelper)
                {
                    if (db == null)
                    {
                        var client = new MongoClient(connStr);
                        db = client.GetDatabase(dbName);
                    }
                }
            }
            return db;
        }
    }
}

封装BaseEntity.cs 基础实体类

using System;
using MongoDB.Bson;

namespace MongoDbDemo.MongoDb
{
    /// <summary>
    /// model
    /// </summary>
    public abstract class BaseEntity
    {
        public BaseEntity()
        {
            this.Id = ObjectId.GenerateNewId();
            this.State = 0;
        }
        /// <summary>
        /// id
        /// </summary>
        public ObjectId Id { get; set; }

        /// <summary>
        ///状态 0正常 1禁用
        /// </summary>
        public int State { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime UpdateTime { get; set; }
    }
}

封装MongoDbHelper.cs 操作类

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbDemo.Util;

namespace MongoDbDemo.MongoDb
{
    public class MongoDbHelper<T> where T : BaseEntity
    {
        #region 构造
        /// <summary>
        /// The database
        /// </summary>
        private IMongoDatabase db = null;

        /// <summary>
        /// The collection
        /// </summary>
        private IMongoCollection<T> collection = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="MongoDbHelper{T}"/> class.
        /// </summary>
        public MongoDbHelper()
        {
            this.db = ContextDb.GetDb();
            collection = db.GetCollection<T>(typeof(T).Name);
        }
        #endregion

        #region 新增
        /// <summary>
        /// 新增一个实体
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public MessageInfo Insert(T entity)
        {
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            collection.InsertOne(entity);
            return new MessageInfo() { IsSuccess = true, Message = entity.Id.ToString() };
        }
        /// <summary>
        /// 新增一个实体
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public MessageInfo InsertAsync(T entity)
        {
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            collection.InsertOneAsync(entity);
            return new MessageInfo() { IsSuccess = true, Message = entity.Id.ToString() };
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list"></param>
        public void InsertsAsync(List<T> list)
        {
            list.ForEach(t => t.CreateTime = DateTime.Now);
            list.ForEach(t => t.UpdateTime = DateTime.Now);
            collection.InsertManyAsync(list);
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改实体的一个字段
        /// </summary>
        /// <param name="id">数据ID</param>
        /// <param name="field">字段</param>
        /// <param name="value">值</param>
        public void ModifyAsync(string id, string field, string value)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq("Id", ObjectId.Parse(id));
            UpdateDefinition<T> updated = Builders<T>.Update.Set(field, value);
            collection.UpdateOneAsync(filter, updated);
        }

        /// <summary>
        /// 更新一个实体
        /// </summary>
        /// <param name="entity"></param>
        public void UpdateAsync(T entity)
        {
            try
            {
                T old = collection.Find(e => e.Id.Equals(entity.Id))?.FirstOrDefault();
                if (old == null)
                {
                    return;
                }
                foreach (var prop in entity.GetType().GetProperties())
                {
                    object? newValue = prop.GetValue(entity);
                    object? oldValue = old.GetType().GetProperty(prop.Name)?.GetValue(old);
                    if (newValue != null)
                    {
                        if (oldValue == null)
                        {
                            oldValue = "";
                        }
                        if (!newValue.ToString().Equals(oldValue.ToString()))
                        {
                            old.GetType().GetProperty(prop.Name)?.SetValue(old, newValue.ToString());
                        }
                    }
                }
                old.UpdateTime = DateTime.Now;
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("Id", entity.Id);
                collection.ReplaceOneAsync(filter, old);
            }
            catch (Exception ex)
            {
                var aaa = ex.Message + ex.StackTrace;
                throw;
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除一个实体
        /// </summary>
        /// <param name="entity"></param>
        public void Delete(T entity)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq("Id", entity.Id);
            collection.DeleteOneAsync(filter);
        }

        /// <summary>
        /// 删除一个实体
        /// </summary>
        /// <param name="id">The identifier.</param>
        public void Delete(ObjectId id)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq("Id", id);
            collection.DeleteOneAsync(filter);
        }

        /// <summary>
        /// 根据Id批量删除
        /// </summary>
        public void Deletes(List<ObjectId> list)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.In("Id", list);
            collection.DeleteManyAsync(filter);
        }

        #endregion

        #region 查询
        /// <summary>
        /// 根据id查询一条数据
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public T QueryOne(string id)
        {
            return collection.Find(a => a.Id == ObjectId.Parse(id))?.FirstOrDefault();
        }

        /// <summary>
        /// 根据条件查询一条数据
        /// </summary>
        /// <param name="express">The express.</param>
        /// <returns></returns>
        public T QueryOne(Expression<Func<T, bool>> express)
        {
            return collection.Find(express)?.FirstOrDefault();
        }

        /// <summary>
        /// 查询多条数据
        /// </summary>
        /// <param name="express">The express.</param>
        /// <returns></returns>
        public List<T> QueryList(Expression<Func<T, bool>> express)
        {
            return collection.Find(express)?.ToList();
        }
        #endregion
    }
}

编写MessageInfo.cs 返回类

namespace MongoDbDemo.Util
{
    public class MessageInfo
    {
        /// <summary>
        ///是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        ///内容
        /// </summary>
        public string Message { get; set; }
    }
}

4、调用

using System;
using MongoDbDemo.Model;
using MongoDbDemo.MongoDb;
using MongoDbDemo.Util;

namespace MongoDbDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime strtime=DateTime.Now;
            MongoDbHelper<UserInfo> db = new MongoDbHelper<UserInfo>();
            for (int i = 0; i < 1000000; i++)
            {
                MessageInfo ret = db.Insert(new UserInfo
                {
                    UserName = "王二"+i,
                    UserPass = "111222333"
                });
            }
            DateTime enttime = DateTime.Now;
            double num = (enttime - strtime).TotalSeconds;
            Console.WriteLine(num);
            Console.ReadKey();
        }
    }
}

image.png


image.png

CarsonIT 微信扫码关注公众号 策略、创意、技术

留下您的脚步

 

最近评论

查看更多>>

站点统计

总文章数:275 总分类数:18 总评论数:88 总浏览数:124.82万

精选推荐

阅读排行

友情打赏

请打开您的微信,扫一扫