C# 操作MongoDb增删改查示例

使用NuGet引用MongoDb.Driver

static void Main(string[] args)
        {
            MongoDbHelper db = new MongoDbHelper();
            var model = new MongoTestEntity()
            {
                C1 = "lijie",
                C2 = "100",
                C3 = "简单了福建省领导福建省代理费三两份就是抵抗力福建省范德萨了附加",
                C4 = DateTime.Now.ToString()
            };
            
            Console.WriteLine("插入数据:" + JsonConvert.SerializeObject(model));
            db.Insert(model);

            var list  = db.QueryAll();
            foreach (var item in list)
            {
                Console.WriteLine("查询数据:" + item.C1);
            }

            db.Modify(list.FirstOrDefault().Id.ToString(),"C1","zhangsan");
            Console.Read();
        }
public class DB
    {
        private static readonly string connStr = "mongodb://127.0.0.1:27017";

        private static readonly string dbName = "mongodbtest";

        private static IMongoDatabase db = null;

        private static readonly object lockHelper = new object();

        private DB() { }

        public static IMongoDatabase GetDb()
        {
            if (db == null)
            {
                lock (lockHelper)
                {
                    if (db == null)
                    {
                        var client = new MongoClient(connStr);
                        db = client.GetDatabase(dbName);
                    }
                }
            }
            return db;
        }
    }
public class MongoDbHelper where T : BaseEntity
    {
        private IMongoDatabase db = null;

        private IMongoCollection collection = null;

        public MongoDbHelper()
        {
            this.db = DB.GetDb();
            collection = db.GetCollection(typeof(T).Name);
        }
        /// 
        /// 新增
        /// 
        /// 
        /// 
        public T Insert(T entity)
        {
            var flag = ObjectId.GenerateNewId();
            entity.GetType().GetProperty("Id").SetValue(entity, flag);
            entity.State = "y";
            entity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            entity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            collection.InsertOneAsync(entity);
            return entity;
        }
        /// 
        /// 修改
        /// 
        /// 
        /// 
        /// 
        public void Modify(string id, string field, string value)
        {
            var filter = Builders.Filter.Eq("Id", ObjectId.Parse(id));
            var updated = Builders.Update.Set(field, value);
            UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
        }
        /// 
        /// 更新
        /// 
        /// 
        public void Update(T entity)
        {
            try
            {
                var old = collection.Find(e => e.Id.Equals(entity.Id)).ToList().FirstOrDefault();

                foreach (var prop in entity.GetType().GetProperties())
                {
                    var newValue = prop.GetValue(entity);
                    var 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.State = "n";
                old.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var filter = Builders.Filter.Eq("Id", entity.Id);
                ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
            }
            catch (Exception ex)
            {
                var aaa = ex.Message + ex.StackTrace;
                throw;
            }
        }
        /// 
        /// 删除
        /// 
        /// 
        public void Delete(T entity)
        {
            var filter = Builders.Filter.Eq("Id", entity.Id);
            collection.DeleteOneAsync(filter);
        }
        /// 
        /// 根据id查询一条数据
        /// 
        /// 
        /// 
        public T QueryOne(string id)
        {
            return collection.Find(a => a.Id == ObjectId.Parse(id)).ToList().FirstOrDefault();
        }
        /// 
        /// 查询所有数据
        /// 
        /// 
        public List QueryAll()
        {
            return collection.Find(a => a.State != "").ToList();
        }
        /// 
        /// 根据条件查询一条数据
        /// 
        /// 
        /// 
        public T QueryByFirst(Expression> express)
        {
            return collection.Find(express).ToList().FirstOrDefault();
        }
        /// 
        /// 批量添加
        /// 
        /// 
        public void InsertBatch(List list)
        {
            collection.InsertManyAsync(list);
        }
        /// 
        /// 根据Id批量删除
        /// 
        public void DeleteBatch(List list)
        {
            var filter = Builders.Filter.In("Id", list);
            collection.DeleteManyAsync(filter);
        }

        /// 
        /// 未添加到索引的数据
        /// 
        /// 
        public List QueryToLucene()
        {
            return collection.Find(a => a.State.Equals("y") || a.State.Equals("n")).ToList();
        }
    }
public class MongoTestEntity : BaseEntity
    {
        public string C1 { get; set; }
        public string C2 { get; set; }
        public string C3 { get; set; }
        public string C4 { get; set; }
    }
    public abstract class BaseEntity
    {
        public ObjectId Id { get; set; }

        public string State { get; set; }

        public string CreateTime { get; set; }

        public string UpdateTime { get; set; }
    }

 

你可能感兴趣的:(.net,数据库)