C#版的mongodb最新的官方驱动2.4.0版本

已经升级了mongodb至最新的3.4的版本,我想想也该把驱动升到最新的了,我用的驱动还是1.7的版本呢,之前几次想升级,都是因为升级驱动需要改动的代码太大了,升级的成本很高,所以懒得动,就这么的用了几年了。但是现在出了很多新功能,如果不升级的话,根本用不了,比如Lookup等功能。想想咬牙就升级了。驱动DLL一换,就发现代码全报错了。以前的IMongoQuery等方法全用不了的。有一些方法也不见了,在修改的过程中,只能写边修改边写代码测试,一个一个测试它提供的新方法。等了解了新的驱动后,觉得改动还是非常大的,将Query,Update等都集成到了一个叫Builders的类中了,把Update中有关SetWrapped的方法全删了,最后试了半天,才发现,SetWrapped的方法,可以直接用新方法中的Set就可以搞定了,而AddToSetWrapped方法只需要用AddToSet方法就行了。

     带给我的最大震憾是,新的写法可以完全用LINQ搞定,终于不用再去管mongodb的那个实体类的映射了,在操作中,完全用类的字段就可以搞定,我把的一个类的方法贴出来供大家参考一下。

 

 

    public class Content
    {
        [BsonId]
        public ObjectId Id { get; set; }
        [BsonElement("t")]
        public string Title { get; set; } 

        [BsonElement("d")]
        public string Detail { get; set; } 

        [BsonElement("a")]
        public string Author { get; set; } 


        [BsonElement("ct")]
        public double CreateTime { get; set; } 

        [BsonElement("click")]
        public int Click { get; set; } 

        [BsonElement("img")]
        public string Img { get; set; }

        [BsonElement("f")]
        public bool IsFinished { get; set; } 

        [BsonElement("type")]
        public int Type { get; set; } 
    }

老的操作类的土鳖方法是这样的

   public class ContentInfo : DBBase
    {
        public static void InsertContent(string title, string detail, string author, string img, int type)
        {
            Content k = new Content
            {
                Author = author,
                Detail = detail,
                Img = img,
                Title = title,
                Click = 0,
                Type = type,
                CreateTime = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000)
            };
            try
            {
                var collection = _database.GetCollection<Content>("content");
                collection.Insert(k);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public static void UpdateContent(string id, string title, string detail, string author, string img, int type)
        {
            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.EQ("_id", new ObjectId(id));
            UpdateBuilder up = new UpdateBuilder();
            up.Set("t", title);
            up.Set("d", detail);
            up.Set("a", author);
            up.Set("img", img);
            up.Set("type", type);
            collection.Update(query, up, UpdateFlags.Upsert);
        }


        public static Content Get(string id)
        {
            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.EQ("_id", new ObjectId(id));
            IMongoUpdate update = Update.Inc("click", 1);
            collection.Update(query, update);
            var results = collection.FindOneAs<Content>(query);
            return results;
        }
        public static List<Content> GetContentList(int pageIndex, int pageSize, out int count, bool isShow = true)
        {

            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.GT("click", -100);
            if (isShow)
            {
                query = Query.And(query, Query.EQ("f", true));
            }

            SortByDocument sort = new SortByDocument { { "ct", -1 } };
            var num = collection.Count(query);
            count = Convert.ToInt32(num);
            var results = collection.FindAs<Content>(query).SetSortOrder(sort).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize);
            return results.ToList();

        }

        public static List<Content> GetContentTypeList(int type, int pageIndex, int pageSize, out int count)
        {

            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.GT("click", -100);

            query = Query.And(query, Query.EQ("f", true));
            query = Query.And(query, Query.EQ("type", type));

            SortByDocument sort = new SortByDocument { { "ct", -1 } };
            var num = collection.Count(query);
            count = Convert.ToInt32(num);
            var results = collection.FindAs<Content>(query).SetSortOrder(sort).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize);
            return results.ToList();

        }



        public static List<Content> GetContentSiteMap()
        {
            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.GT("click", -100);

            query = Query.And(query, Query.EQ("f", true));


            SortByDocument sort = new SortByDocument { { "ct", -1 } };
            FieldsDocument fd = new FieldsDocument();
            fd.Add("d", 0);
            var results = collection.FindAs<Content>(query).SetFields(fd).SetSortOrder(sort);
            return results.ToList();
        }




        public static void UpdateContentTrue(string id)
        {
            var collection = _database.GetCollection<Content>("content");
            IMongoQuery query = Query.EQ("_id", new ObjectId(id));
            UpdateBuilder up = new UpdateBuilder();
            up.Set("f", true);
            up.Set("ct", ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000));
            collection.Update(query, up, UpdateFlags.Upsert);
        }
  }

而新的方法是这样的:

   public class ContentInfo : DBBase
    {
        public static void InsertContent(string title, string detail, string author, string img, int type)
        {
            Content k = new Content
            {
                Author = author,
                Detail = detail,
                Img = img,
                Title = title,
                Click = 0,
                Type = type,
                CreateTime = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000)
            };
            try
            {
                var collection = _database.GetCollection<Content>("content");
                collection.InsertOne(k);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public static void UpdateContent(string id, string title, string detail, string author, string img, int type)
        {
            var collection = _database.GetCollection<Content>("content");
            var filter = Builders<Content>.Filter.Eq(x => x.Id, new ObjectId(id));
            var up = Builders<Content>.Update
            .Set(x => x.Title, title)
            .Set(x => x.Detail, detail)
            .Set(x => x.Author, author)
            .Set(x => x.Img, img)
            .Set(x => x.Type, type);

            collection.UpdateOneAsync(filter, up);
        }


        public static Content Get(string id)
        {
            var collection = _database.GetCollection<Content>("content");
            var filter = Builders<Content>.Filter.Eq(x => x.Id, new ObjectId(id));
            var up = Builders<Content>.Update.Inc(x => x.Click, 1);
            var results = collection.FindOneAndUpdate(filter, up);
            return results;
        }
        public static List<Content> GetContentList(int pageIndex, int pageSize, out int count, bool isShow = true)
        {

            var collection = _database.GetCollection<Content>("content");

            var builder = Builders<Content>.Filter;
            var filter = builder.Gt(x => x.Click, -100);

            if (isShow)
            {
                filter = builder.And(filter, builder.Eq(x => x.IsFinished, true));
            }

            var sort = Builders<Content>.Sort.Descending(x => x.CreateTime);



            var num = collection.Count(filter);
            count = Convert.ToInt32(num);
            var results = collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize);
            return results.ToList();

        }

        public static List<Content> GetContentTypeList(int type, int pageIndex, int pageSize, out int count)
        {

            var collection = _database.GetCollection<Content>("content");
            var filter = Builders<Content>.Filter.Where(x => x.Click > -100 && x.IsFinished == true && x.Type == type);

            var sort = Builders<Content>.Sort.Descending(x => x.CreateTime);

            var num = collection.Count(filter);
            count = Convert.ToInt32(num);
            var results = collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize);
            return results.ToList();

        }



        public static List<Content> GetContentSiteMap()
        {
            var collection = _database.GetCollection<Content>("content");
            var filter = Builders<Content>.Filter.Where(x => x.Click > -100 && x.IsFinished == true);

            var sort = Builders<Content>.Sort.Descending(x => x.CreateTime);

            var project = Builders<Content>.Projection.Exclude(x => x.Detail);

            var results = collection.Find(filter).Project<Content>(project).Sort(sort);
            return results.ToList();
        }




        public static void UpdateContentTrue(string id)
        {
            var collection = _database.GetCollection<Content>("content");
            var filter = Builders<Content>.Filter.Eq(x => x.Id, new ObjectId(id));
            var up = Builders<Content>.Update
                .Set(x => x.IsFinished, true)
                .Set(x => x.CreateTime, ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000));

            var results = collection.FindOneAndUpdate(filter, up);
        }

    }

新的里面已经完全看不到了mongodb数据库中的字段名了,完全可以用lambda表达式完成这些操作了,对程序员来说,操作简便了,不需要再去对照映射关系了,也降低了一些程序员的入门门槛,有些基础的操作,程序员甚至不需要了解mongodb,只要会写LINQ就可以完成了。这么多的好处,我觉得将数据库和驱动都升级到最新版还是挺值的。但是注意,1.X版本的驱动和2.X版本的驱动是完全不一样的,是破坏性升级,如果想要更换这个驱动,代码是一定要重新写的,所以大家也别光看到好处,也要计算一下成本。

posted @ 2017-05-16 22:30  superstar  阅读(2141)  评论(1编辑  收藏  举报