>  기사  >  백엔드 개발  >  MongoDb C# 래퍼 类 (MongoDb 드라이버 1.9)

MongoDb C# 래퍼 类 (MongoDb 드라이버 1.9)

黄舟
黄舟원래의
2017-03-01 10:45:391451검색

1. mongoDb 드라이버 패키지 설치

2. Wrapper 클래스 사용:

 public class MongoDbWrapper : IDisposable
    {
        private MongoServer _server;
        private MongoDatabase _db;
        public MongoDbWrapper()
        {
            var uri = ConfigurationSettings.AppSettings["mongoUrl"];

            var url = new MongoUrl(uri);
            var client = new MongoClient(url);
            _server = client.GetServer();
            _db = _server.GetDatabase(url.DatabaseName);
        }

        public MongoDbWrapper BatchAdd<T>(T[] objArray, string collectionName)
        {
            var collection = _db.GetCollection<T>(collectionName);
            collection.InsertBatch(objArray);

            return this;
        }

        public MongoDbWrapper Add<T>(T obj, string collectionName)
        {
            var collection = _db.GetCollection<T>(collectionName);
            collection.Insert(obj);

            return this;
        }

        /// <summary>
        /// e.g. { "Age", new BsonDocument { { "$gte", 10 } } }
        /// </summary>
        /// <param name="query"></param>
        /// <param name="collectionName"></param>
        public void DeleteBy<T>(Expression<Func<T, bool>> whereExp, string collectionName)
        {
            var collection = _db.GetCollection<T>(collectionName);
            collection.Remove(Query<T>.Where(whereExp));
        }

        public void Update<T>(IMongoQuery query, string collectionName, T newObj) where T : IMongoUpdate
        {
            var collection = _db.GetCollection<T>(collectionName);
            collection.Update(query, newObj);
        }

        public IEnumerable<T> Search<T>(Expression<Func<T, bool>> whereExp, string collectionName)
        {
            var collection = _db.GetCollection<T>(collectionName);
            return collection.Find(Query<T>.Where(whereExp)).ToList();
        }

        public T Single<T>(Expression<Func<T, bool>> whereExp, string collectionName)
        {
            return Search(whereExp, collectionName).Single();
        }

        public void RemoveCollection(string collectionName)
        {
            _db.DropCollection(collectionName);
        }

        public void Dispose()
        {
            _server.Disconnect();
        }
    }

3 일부 관련 작업의 사용 예

查询
var driver = dbWrapper.Single<Driver>(d => d.Name == name, DbCollectionName.For<Driver>());
var drivers = dbWrapper.Search<Driver>(d => d.Name == name, DbCollectionName.For<Driver>());

删除
dbWrapper.DeleteBy<Job>(j => j.Id == id, DbCollectionName.For<PublicQueue>());

从集合移除
var updatingNw = Update<Network>.Pull(nw => nw.Jobs, aJobFromQueue);
                dbWrapper.Update(Query<Network>.Where(n => n.Name == Name), DbCollectionName.For<Network>(), updatingNw);

添加新项到集合
var updatingDp = Update<Dispatcher>.AddToSet<dynamic>(d => d.PendingJobs, aJobFromQueue);
                dbWrapper.Update(Query<Dispatcher>.Where(d => d.Name == name), DbCollectionName.For<Dispatcher>(), updatingDp);

更新
dbWrapper.Update(Query<Network>.Where(n => n.Name == Name), DbCollectionName.For<Network>(), updatingNw);

위는 MongoDb C# Wrapper 클래스입니다. (MongoDb Driver 1.9), 더 많은 관련 내용을 보려면 PHP 중국어 웹사이트(www.php.cn)를 주목하세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.