示例#1
0
        /// <summary>
        /// 根据文档名称、查询条件获取文档指定列的数据
        /// </summary>
        /// <typeparam name="T">文档类型</typeparam>
        /// <param name="colName">文档名称</param>
        /// <param name="query">查询条件</param>
        /// <param name="fields">列列表</param>
        /// <returns>文档符合条件所有数据</returns>
        public static List <T> Get <T>(string colName, IMongoQuery query, IMongoFields fields)
        {
            var mongo      = MongoManager.getDB();
            var collection = mongo.GetCollection <T>(colName);

            return(collection.FindAs <T>(query).SetFields(fields).ToList());
        }
示例#2
0
        public async void FindAndRemoveAsyncTest()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));

            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var               update            = Update.Set("Message", MONGO_EDITED_TEXT);
            var               sortBy            = SortBy.Descending("TimeStamp");
            IMongoFields      fields            = Fields.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();

            findAndRemoveArgs.Query  = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;

            FindAndModifyResult result = await _databaseUpdater.FindAndRemoveAsync <Entry>(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Ok);
            Assert.IsNull(result.ErrorMessage);
            Assert.IsNotNull(result.ModifiedDocument);

            results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
示例#3
0
        public MongoCursor Find(
            string collectionName,
            IMongoQuery query,
            long?limit,
            long?skip,
            IMongoFields fields,
            IMongoSortBy sortBy)
        {
            var c = GetExistingCollection(collectionName);

            var q = c.Find(query);

            if (limit.HasValue)
            {
                q.SetLimit((int)limit.Value);
            }

            if (skip.HasValue)
            {
                q.SetSkip((int)skip.Value);
            }

            if (fields != null)
            {
                q.SetFields(fields);
            }

            if (sortBy != null)
            {
                q.SetSortOrder(sortBy);
            }

            return(q);
        }
示例#4
0
        public QueryOperation(
            string databaseName,
            string collectionName,
            BsonBinaryReaderSettings readerSettings,
            BsonBinaryWriterSettings writerSettings,
            int batchSize,
            IMongoFields fields,
            QueryFlags flags,
            int limit,
            BsonDocument options,
            IMongoQuery query,
            ReadPreference readPreference,
            IBsonSerializationOptions serializationOptions,
            IBsonSerializer serializer,
            int skip)
            : base(databaseName, collectionName, readerSettings, writerSettings)
        {
            _batchSize            = batchSize;
            _fields               = fields;
            _flags                = flags;
            _limit                = limit;
            _options              = options;
            _query                = query;
            _readPreference       = readPreference;
            _serializationOptions = serializationOptions;
            _serializer           = serializer;
            _skip = skip;

            // since we're going to block anyway when a tailable cursor is temporarily out of data
            // we might as well do it as efficiently as possible
            if ((_flags & QueryFlags.TailableCursor) != 0)
            {
                _flags |= QueryFlags.AwaitData;
            }
        }
示例#5
0
        /// <summary>
        /// 查询数据,增加需要的参数字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="collectionName"></param>
        /// <param name="filter"></param>
        /// <param name="exceptFields"></param>
        /// <param name="containtFields"></param>
        /// <returns></returns>
        public List <T> Query <T>(IMongoQuery query, string collectionName, BaseFilter filter, string[] exceptFields, string[] containtFields)
        {
            MongoCollection collection = GetMongoCollection(collectionName);

            filter.RecordCount = Convert.ToInt32(collection.Count(query));
            SortByDocument  sortByDocument = GetSortFromStr(filter.OrderbyStr);
            MongoCursor <T> mongoCursor    = collection.FindAs <T>(query);

            //查询性能分析
            //BsonDocument document = collection.FindAs<T>(query).Explain();
            if (sortByDocument != null)
            {
                mongoCursor = mongoCursor.SetSortOrder(sortByDocument);
            }
            IMongoFields fields = GetFields(exceptFields, containtFields);

            if (fields != null)
            {
                mongoCursor = mongoCursor.SetFields(fields);
            }

            if (filter.PageSize == 0)
            {
                filter.PageSize = DefaultPageSize;
            }
            if (filter.PageNo == 0)
            {
                filter.PageNo = DefaultPageNo;
            }
            return(mongoCursor.SetSkip(filter.PageSize * (filter.PageNo - 1)).SetLimit(filter.PageSize).ToListEntity <T>());
        }
        public void FindAndRemoveTest2()
        {
            _AsyncDelegateUpdaterT.AsyncFindAndRemoveCompleted -= new FindAndRemoveCompletedEvent(_updaterAsync_AsyncFindAndRemoveCompleted);

            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));

            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var               update            = Update.Set("Message", MONGO_EDITED_TEXT);
            var               sortBy            = SortBy.Descending("TimeStamp");
            IMongoFields      fields            = Fields.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();

            findAndRemoveArgs.Query  = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;
            _AsyncDelegateUpdaterT.FindAndRemoveAsync(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);
            Thread.Sleep(2000); // wait 2 seconds to show that event handler will not pick up callback

            Assert.IsNull(_writeConcernResult);

            results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
示例#7
0
        public void FindAndRemoveTest1()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));

            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var               update            = Update.Set("Message", MONGO_EDITED_TEXT);
            var               sortBy            = SortBy.Descending("TimeStamp");
            IMongoFields      fields            = Fields.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();

            findAndRemoveArgs.Query  = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;
            _AsyncDelegateUpdaterT.FindAndRemoveAsync(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);
            _updaterAutoResetEvent.WaitOne();

            Assert.IsTrue(_findAndModifyResult.Ok, "FindAndModifyResult from FindAndModify not OK");
            Assert.IsNull(_findAndModifyResult.ErrorMessage);
            Assert.IsNotNull(_findAndModifyResult.ModifiedDocument);

            results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
示例#8
0
        public List <T> FullTextSearch <T>(string keyword, IMongoQuery query, IMongoFields fields, int limit)
        {
            var _result = FullTextSearch <T>("english", keyword, query, fields, limit);

            var _val = _result.Response["results"].AsBsonDocument;

            return(BsonSerializer.Deserialize <List <T> >(_val));
        }
 /// <summary>
 /// Sets the fields that will be returned from the server.
 /// </summary>
 /// <param name="fields">The fields that will be returned from the server.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor SetFields(IMongoFields fields)
 {
     if (_isFrozen)
     {
         ThrowFrozen();
     }
     _fields = fields;
     return(this);
 }
 public IQueryable <TEntity> Find(IMongoQuery query, IMongoFields fields, int index, int limit)
 {
     return(GetTypeCollection <TEntity>(MappingCfg.ToDatabase, MappingCfg.ToCollection)
            .Find(query)
            .SetFields(fields)
            .SetSkip(index * limit)
            .SetLimit(limit)
            .AsQueryable());
 }
 /// <summary>
 /// Sets the fields that will be returned from the server.
 /// </summary>
 /// <param name="fields">The fields that will be returned from the server.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor SetFields(params string[] fields)
 {
     if (_isFrozen)
     {
         ThrowFrozen();
     }
     _fields = Builders.Fields.Include(fields);
     return(this);
 }
示例#12
0
 /// <summary>
 /// Finds one matching document using the query and sortBy parameters and applies the specified update to it.
 /// </summary>
 /// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
 /// <param name="sortBy">The sort order to select one of the matching documents.</param>
 /// <param name="update">The update to apply to the matching document.</param>
 /// <param name="fields">Which fields of the modified document to return in the <see cref="FindAndModifyResult"/>.</param>
 /// <param name="returnNew">Whether to return the new or old version of the modified document in the <see cref="FindAndModifyResult"/>.</param>
 /// <param name="upsert">Whether to do an upsert if no matching document is found.</param>
 /// <returns>A <see cref="FindAndModifyResult"/>.</returns>
 public virtual FindAndModifyResult FindAndModify(
     IMongoQuery query,
     IMongoSortBy sortBy,
     IMongoUpdate update,
     IMongoFields fields,
     bool returnNew,
     bool upsert)
 {
     return(_collection.FindAndModify(query, sortBy, update, fields, returnNew, upsert));
 }
 internal MongoQueryMessage(BsonBuffer buffer, BsonBinaryWriterSettings writerSettings, string collectionFullName, QueryFlags flags, int numberToSkip, int numberToReturn, IMongoQuery query, IMongoFields fields)
     : base(MessageOpcode.Query, buffer, writerSettings)
 {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.numberToSkip = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query = query;
     this.fields = fields;
 }
示例#14
0
 internal MongoQueryMessage(BsonBuffer buffer, BsonBinaryWriterSettings writerSettings, string collectionFullName, QueryFlags flags, int numberToSkip, int numberToReturn, IMongoQuery query, IMongoFields fields)
     : base(MessageOpcode.Query, buffer, writerSettings)
 {
     this.collectionFullName = collectionFullName;
     this.flags          = flags;
     this.numberToSkip   = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query          = query;
     this.fields         = fields;
 }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : this(null, writerSettings, collectionFullName, flags, numberToSkip, numberToReturn, query, fields)
 {
 }
        public virtual IQueryable <T1> Find <T1>(string mongoQuery, IMongoFields fields, dynamic parameters = null, string collectionName = "")
        {
            IMongoQuery query = ProcessQuery(mongoQuery, parameters);

            if (string.IsNullOrEmpty(collectionName))
            {
                return(GetCollection(CollectionName).FindAs <T1>(query).SetFields(fields).SetFlags(QueryFlags.NoCursorTimeout).AsQueryable());
            }

            return(GetCollection(collectionName).FindAs <T1>(query).SetFields(fields).SetFlags(QueryFlags.NoCursorTimeout).AsQueryable());
        }
 internal MongoQueryMessage(
     MongoServer server,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields
 ) :
     this(server, collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null) {
 }
示例#18
0
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : this(null, writerSettings, collectionFullName, flags, numberToSkip, numberToReturn, query, fields)
 {
 }
 /// <summary>
 /// Sets the fields that will be returned from the server.
 /// </summary>
 /// <param name="fields">The fields that will be returned from the server.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor <TDocument> SetFields(
     params string[] fields
     )
 {
     if (isFrozen)
     {
         ThrowFrozen();
     }
     this.fields = Builders.Fields.Include(fields);
     return(this);
 }
 /// <summary>
 /// Sets the fields that will be returned from the server.
 /// </summary>
 /// <param name="fields">The fields that will be returned from the server.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor <TDocument> SetFields(
     IMongoFields fields
     )
 {
     if (isFrozen)
     {
         ThrowFrozen();
     }
     this.fields = fields;
     return(this);
 }
示例#21
0
 internal MongoQueryMessage(
     MongoConnection connection,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields
     ) :
     this(connection, collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null)
 {
 }
示例#22
0
        /// <summary>
        /// mongo不分页查询,增加字段筛选
        /// </summary>
        /// <typeparam name="J"></typeparam>
        /// <param name="query"></param>
        /// <param name="collectionName"></param>
        /// <param name="orderStr"></param>
        /// <param name="exceptFields"></param>
        /// <param name="containtFields"></param>
        /// <returns></returns>
        public List <J> QueryAll <J>(IMongoQuery query, string collectionName, string orderStr,
                                     string[] exceptFields, string[] containtFields)
        {
            MongoCollection collection  = GetMongoCollection(collectionName);
            MongoCursor <J> mongoCursor = collection.FindAs <J>(query);
            IMongoFields    fields      = GetFields(exceptFields, containtFields);

            if (fields != null)
            {
                mongoCursor.SetFields(fields);
            }
            return(ReturnList <J>(mongoCursor, orderStr));
        }
示例#23
0
        /// <summary>
        /// 显示全部,支持排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sortBy"></param>
        /// <param name="fields">显示出了ID之外的另外一些列的值</param>
        /// <returns></returns>
        public static List <T> SelectSortR <T>(string sortByJson, params string[] fields)
        {
            string       collectionName = typeof(T).Name;
            IMongoFields field          = Fields.Include(fields);

            Array.Clear(fields, 0, fields.Length);
            fields = null;
            MongoCollection collection         = MongoCollection(collectionName);
            BsonDocument    bsonSortByDocument = BsonSerializer.Deserialize(sortByJson, typeof(BsonDocument)) as BsonDocument;
            SortByDocument  sortByDocument     = new SortByDocument(bsonSortByDocument);

            return(collection.FindAllAs <T>().SetFields(field).SetSortOrder(sortByDocument).ToList <T>());
        }
示例#24
0
        public static List <T> SelectR <T>(int pageSize, int pageIndex, string queryJson, params string[] fields)
        {
            string       collectionName = typeof(T).Name;
            IMongoFields field          = Fields.Include(fields);

            Array.Clear(fields, 0, fields.Length);
            fields = null;
            MongoCollection collection        = MongoCollection(collectionName);
            BsonDocument    bsonQueryDocument = BsonSerializer.Deserialize(queryJson, typeof(BsonDocument)) as BsonDocument;
            QueryDocument   queryDocument     = new QueryDocument(bsonQueryDocument);

            return(collection.FindAs <T>(queryDocument).SetFields(field).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize).ToList <T>());;
        }
示例#25
0
        public static BsonDocument ToGroupDocument <T>(this IMongoFields fields)
        {
            var _coll = GetCollectionName <T>();

            var _sums = new BsonDocument {
                { "_id", new BsonDocument(_coll, string.Format("${0}", _coll)) }
            };

            foreach (string _name in fields.ToBsonDocument().Names)
            {
                _sums.Add(_name, new BsonDocument("$sum", string.Format("${0}", _name)));
            }

            return(new BsonDocument("$group", _sums));
        }
示例#26
0
        /// <summary>
        /// 条件查询,不支持排序(远程调用方法)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static List <T> SelectR <T>(string queryJson)
        {
            string collectionName = typeof(T).Name;

            string[]     fields = GetFields <T>();
            IMongoFields field  = Fields.Include(fields);

            Array.Clear(fields, 0, fields.Length);
            fields = null;
            MongoCollection collection        = MongoCollection(collectionName);
            BsonDocument    bsonQueryDocument = BsonSerializer.Deserialize(queryJson, typeof(BsonDocument)) as BsonDocument;
            QueryDocument   queryDocument     = new QueryDocument(bsonQueryDocument);

            return(collection.FindAs <T>(queryDocument).SetFields(field).ToList <T>());
        }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : base(MessageOpcode.Query, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _flags = flags;
     _numberToSkip = numberToSkip;
     _numberToReturn = numberToReturn;
     _query = query;
     _fields = fields;
 }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : base(MessageOpcode.Query, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _flags          = flags;
     _numberToSkip   = numberToSkip;
     _numberToReturn = numberToReturn;
     _query          = query;
     _fields         = fields;
 }
 internal MongoQueryMessage(
     MongoServer server,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields,
     BsonBuffer buffer
 ) :
     base(server, MessageOpcode.Query, buffer) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.numberToSkip = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query = query;
     this.fields = fields;
 }
示例#30
0
        public MongoCursor FindAll(string collectionName, IMongoFields fields, IMongoSortBy sortBy)
        {
            var c = GetExistingCollection(collectionName);

            var q = c.FindAll();

            if (fields != null)
            {
                q.SetFields(fields);
            }

            if (sortBy != null)
            {
                q.SetSortOrder(sortBy);
            }

            return(q);
        }
示例#31
0
 internal MongoQueryMessage(
     MongoConnection connection,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields,
     BsonBuffer buffer
     ) :
     base(connection, MessageOpcode.Query, buffer)
 {
     this.collectionFullName = collectionFullName;
     this.flags          = flags;
     this.numberToSkip   = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query          = query;
     this.fields         = fields;
 }
示例#32
0
        /// <summary>
        /// 分页显示,支持条件,支持排序,返回纪录数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="query"></param>
        /// <param name="sortBy"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public static List <T> SelectR <T>(int pageSize, int pageIndex, string queryJson, string sortByJson, out long recordCount)
        {
            recordCount = 0;
            string collectionName = typeof(T).Name;

            string[]     fields = GetFields <T>();
            IMongoFields field  = Fields.Include(fields);

            Array.Clear(fields, 0, fields.Length);
            fields = null;
            MongoCollection collection        = MongoCollection(collectionName);
            BsonDocument    bsonQueryDocument = BsonSerializer.Deserialize(queryJson, typeof(BsonDocument)) as BsonDocument;
            QueryDocument   queryDocument     = new QueryDocument(bsonQueryDocument);
            BsonDocument    bsonSortDocument  = BsonSerializer.Deserialize(sortByJson, typeof(BsonDocument)) as BsonDocument;
            SortByDocument  sortByDocument    = new SortByDocument(bsonSortDocument);

            recordCount = collection.Count(queryDocument);
            return(collection.FindAs <T>(queryDocument).SetFields(field).SetSortOrder(sortByDocument).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize).ToList <T>());
        }
示例#33
0
        public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
        {
            foreach (var document in QueryCompiler.Query(Documents, Documents2, query, sortBy, 0, 0))
            {
                // if old is needed then deep(!) clone before update //_131103_185751
                BsonDocument output = null;
                if (!returnNew)
                    output = document.DeepClone().AsBsonDocument;

                UpdateDocument(document, UpdateCompiler.GetFunction((IConvertibleToBsonDocument)update, null, false));

                if (returnNew)
                    output = document;

                // project
                if (fields != null)
                {
                    var project = FieldCompiler.GetFunction(fields);
                    output = project(output);
                }

                // if old is needed then return it as already deep cloned
                result = new SimpleUpdateResult(1, true);
                if (!returnNew && documentType == typeof(Dictionary))
                    return new Dictionary(output);
                else
                    // deserialize to required type
                    return BsonSerializer.Deserialize(output, documentType);
            }

            // not found, insert
            if (upsert)
            {
                var document = InsertNewDocument(query, update);

                result = new SimpleUpdateResult(1, false);
                return returnNew ? BsonSerializer.Deserialize(document, documentType) : null;
            }

            result = new SimpleUpdateResult(0, false);
            return null;
        }
示例#34
0
        /// <summary>
        /// 查询单个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public static T GetR <T>(string queryJson) where T : class
        {
            T      obj            = null;
            string collectionName = typeof(T).Name;

            string[]     fields = GetFields <T>();
            IMongoFields field  = Fields.Include(fields);

            Array.Clear(fields, 0, fields.Length);
            fields = null;
            MongoCollection collection        = MongoCollection(collectionName);
            BsonDocument    bsonQueryDocument = BsonSerializer.Deserialize(queryJson, typeof(BsonDocument)) as BsonDocument;
            QueryDocument   queryDocument     = new QueryDocument(bsonQueryDocument);

            if (collection != null)
            {
                //obj = collection.FindOneAs<T>(queryDocument);
                obj = collection.FindAs <T>(queryDocument).SetFields(field).FirstOrDefault <T>();
            }
            return(obj);
        }
示例#35
0
        /// <summary>
        /// 得到需要的字段
        /// </summary>
        /// <param name="exceptFields">排除字段</param>
        /// <param name="containtFields">包含字段</param>
        /// <returns>字段</returns>
        public IMongoFields GetFields(string[] exceptFields, string[] containtFields)
        {
            IMongoFields fields = null;

            if (exceptFields != null && exceptFields.Length > 0)
            {
                fields = Fields.Exclude(exceptFields);
            }

            if (containtFields != null && containtFields.Length > 0)
            {
                if (fields == null)
                {
                    fields = Fields.Include(containtFields);
                }
                else
                {
                    fields = Fields.Exclude(exceptFields).Include(containtFields);
                }
            }
            return(fields);
        }
示例#36
0
        public static IEnumerable<BsonDocument> 列表专家(int count, IMongoFields fields, IMongoQuery conditions, IEnumerable<long> selected, IEnumerable<long> avoid)
        {
            var ret = new List<BsonDocument>(count);
            var rnd = new Random();
            //var q = Query<专家>.LT(o => o.上次出席评标时间, DateTime.Now.Date.AddDays(-122));
            var q = Query.Null;
            if (null != conditions)
                conditions = Query.And(conditions, q);
            else
                conditions = q;

            if (null != selected && 0 != selected.Count())
            {
                q = Query.NotIn("_id", new BsonArray(selected));
                conditions = Query.And(conditions, q);
            }
            if (null != avoid && 0 != avoid.Count())
            {
                q = Query.NotIn("_id", new BsonArray(avoid));
                conditions = Query.And(conditions, q);
            }
            int total = (int)Mongo.计数<专家>(0, 0, conditions);
            if (total < count) return new List<BsonDocument>();
            var r = Mongo.列表<专家>(0, 0, fields, conditions);
            var ns = new HashSet<int>();
            for (int i = 0; i < count; i++)
            {
                int n;
                do
                {
                    n = rnd.Next(total);
                } while (ns.Contains(n));
                ret.Add(r.ElementAt(n));
                ns.Add(n);
            }
            return ret;
        }
示例#37
0
        public async void FindAndModifyAsyncTest4()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));

            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var          update = Update.Set("Message", MONGO_EDITED_TEXT);
            var          sortBy = SortBy.Descending("TimeStamp");
            IMongoFields fields = Fields.Include("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();

            findAndModifyArgs.Query           = searchQuery;
            findAndModifyArgs.SortBy          = sortBy;
            findAndModifyArgs.Update          = update;
            findAndModifyArgs.Fields          = fields;
            findAndModifyArgs.Upsert          = true;
            findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;

            FindAndModifyResult result = await _databaseUpdater.FindAndModifyAsync <Entry>(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Ok);
            Assert.IsNull(result.ErrorMessage);
            Assert.IsNotNull(result.ModifiedDocument);

            results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
        }
示例#38
0
        public IEnumerable<object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var iter = QueryCompiler.Query(Documents, Documents2, query, sortBy, skip, first);
            if (fields == null)
                return iter.Select(x => BsonSerializer.Deserialize(x, documentType));

            var project = FieldCompiler.GetFunction(fields);
            return iter.Select(project).Select(x => BsonSerializer.Deserialize(x, documentType));
        }
示例#39
0
        public IEnumerable<object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var cursor = _this.FindAs(documentType, query);

            if (modes != QueryFlags.None)
                cursor.SetFlags(modes);

            if (skip > 0)
                cursor.SetSkip(skip);

            if (first > 0)
                cursor.SetLimit(first);

            if (sortBy != null)
                cursor.SetSortOrder(sortBy);

            if (fields != null)
                cursor.SetFields(fields);

            foreach (var it in cursor)
                yield return it;
        }
 public static IEnumerable<BsonDocument> 列表供应商服务记录(int skip, int limit, IMongoFields fields, IMongoQuery conditions = null, bool modifiedDescending = true, IMongoSortBy sorting = null, bool includeDisabled = true, bool includeDeleted = false)
 {
     return Mongo.列表<供应商服务记录>(skip, limit, fields, conditions, modifiedDescending, sorting, includeDisabled, includeDeleted);
 }
示例#41
0
 public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
 {
     var r = _this.FindAndModify(query, sortBy, update, fields, returnNew, upsert);
     result = new FindAndModifyUpdateResult(r);
     return r.GetModifiedDocumentAs(documentType);
 }
示例#42
0
 internal static Func<BsonDocument, BsonDocument> GetFunction(IMongoFields fields)
 {
     var compiler = new FieldCompiler(fields);
     return compiler.Select;
 }
示例#43
0
        // Assume that keys are already unique, so we avoid many checks.
        FieldCompiler(IMongoFields fields)
        {
            var document = ((IConvertibleToBsonDocument)fields).ToBsonDocument();

            if (document.ElementCount == 0)
            {
                _All = true;
                return;
            }

            foreach (var e in document)
            {
                var name = e.Name;
                var value = e.Value;
                if (value.IsNumeric)
                {
                    if (e.Value.ToInt32() != 0)
                    {
                        // include
                        if (_Exclude != null)
                            ThrowMix();

                        if (_Include == null)
                            _Include = new List<string>();

                        if (name != MyValue.Id)
                            _Include.Add(name);
                    }
                    else
                    {
                        // exclude
                        if (name == MyValue.Id)
                        {
                            _Id = false;
                            continue;
                        }

                        if (_Include != null)
                            ThrowMix();

                        if (_Exclude == null)
                            _Exclude = new List<string>();

                        _Exclude.Add(name);
                    }
                    continue;
                }

                BsonDocument selector;
                if (value.BsonType != BsonType.Document || (selector = value.AsBsonDocument).ElementCount != 1)
                    throw new InvalidOperationException("Invalid type of fields.");

                var element = selector.GetElement(0);
                var oper = element.Name;
                var arg = element.Value;

                // case slice
                if (oper == "$slice")
                {
                    if (arg.IsNumeric)
                    {
                        _Slice.Add(name, new int[] { 0, arg.ToInt32() });
                        continue;
                    }

                    BsonArray array;
                    if (arg.BsonType != BsonType.Array || (array = arg.AsBsonArray).Count != 2)
                        throw new InvalidOperationException("Invalid $slice argument.");

                    int n = array[1].ToInt32();
                    if (n <= 0)
                        throw new InvalidOperationException("$slice limit must be positive."); //! DB text

                    _Slice.Add(name, new int[] { array[0].ToInt32(), n });
                    continue;
                }

                // case match

                if (oper != "$elemMatch")
                    throw new InvalidOperationException("Invalid field operator.");

                if (arg.BsonType != BsonType.Document)
                    throw new InvalidOperationException("Invalid field match argument.");

                _ElemMatch.Add(name, QueryCompiler.GetFunction(arg.AsBsonDocument));
            }
        }
示例#44
0
 public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
 {
     var args = new FindAndModifyArgs();
     args.Query = query;
     args.SortBy = sortBy;
     args.Update = update;
     args.Fields = fields;
     args.Upsert = upsert;
     args.VersionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
     var r = _this.FindAndModify(args);
     result = new FindAndModifyUpdateResult(r);
     return r.GetModifiedDocumentAs(documentType);
 }
示例#45
0
 public MongoCursorSettings SetFields(IMongoFields fields)
 {
     this.Fields = fields;
     return this;
 }