编程语言
首页 > 编程语言> > mongo增删改查封装(C#)

mongo增删改查封装(C#)

作者:互联网

Framework版本:.Net Framework 4

ConnectionUtil源码参见:https://www.cnblogs.com/threadj/p/10536273.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using ReligionServer.util;

namespace ReligionServer.repository {
    public class BaseRepository {

        private MongoCollection collection = null;

        //将获取集合对象的方法再一次封装
        private MongoCollection GetColl<T>(String collectionName) {
            return ConnectionUtil.GetCollection<T>(collectionName);
        }
        //-------------------------------------------------------------------------------------------------------------------------------------------

        

        //新增一则记录
        public WriteConcernResult Insert<T>(T t, String collectionName) {
            return GetColl<T>(collectionName).Insert<T>(t);
        }

        //批量新增
        public IEnumerable<WriteConcernResult> InsertBatch<T>(List<T> list, String collectionName) {
            return GetColl<T>(collectionName).InsertBatch(typeof(List<T>), list);
        }
    

        //根据Id查询指定集合名为collectionName的数据
        public T FindById<T>(String id,String collectionName) {
            collection = GetColl<T>(collectionName);
            T t = collection.FindOneByIdAs<T>(ObjectId.Parse(id));
            return t;
        }

        //查询符合条件的第一条数据
        public T FindOneByQuery<T>(IMongoQuery query, String collectionName) {
            collection = GetColl<T>(collectionName);
            T t = collection.FindOneAs<T>(query);
            return t;
        }

        //查询指定集合中符合Query条件的所有的文档
        public List<T> FindList<T>(IMongoQuery query, String collectionName) {
            //MongoCursor<T> cursor = ConnectionUtil.GetCollection<T>(collectionName).FindAs<T>(query);
            List<T> list = GetColl<T>(collectionName).FindAs<T>(query).ToList<T>();
            return list;
        }


        public WriteConcernResult Update<T>(IMongoQuery query, IMongoUpdate update, String collectionName) {
            return GetColl<T>(collectionName).Update(query, update);
        }

        //删除集合名为collectionName的且满足query条件的文档
        public WriteConcernResult Remove<T>(IMongoQuery query, String collectionName) {
            return GetColl<T>(collectionName).Remove(query);
        }
    }
}

 

标签:collectionName,return,mongo,C#,GetColl,using,增删,query,String
来源: https://www.cnblogs.com/threadj/p/10536278.html