public IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetAllTags(IMongoQuery query)
        {
            var dataSet = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);

            foreach (var entity in serverProvider.Database.OsmCompoundQuery(query))
            {
                foreach (var tag in entity.Tags)
                {
                    if (!dataSet.ContainsKey(tag.Key))
                    {
                        dataSet.Add(tag.Key, new HashSet<string>(StringComparer.OrdinalIgnoreCase));
                    }

                    var valueSet = dataSet[tag.Key];
                    if (!valueSet.Contains(tag.Value))
                    {
                        valueSet.Add(tag.Value);
                    }
                }
            }

            var result = dataSet.Select(kv => new KeyValuePair<string, IEnumerable<string>>(kv.Key, kv.Value));

            return result;
        }
 // constructors
 internal MongoDeleteMessage(BsonBinaryWriterSettings writerSettings, string collectionFullName, RemoveFlags flags, IMongoQuery query)
     : base(MessageOpcode.Delete, null, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _flags = flags;
     _query = query;
 }
Beispiel #3
0
        public bool Remove(IMongoQuery query)
        {
            if (query == null)
                throw new ArgumentNullException("Collection must not be null");

            return _connection.GetCurrentCollection().Remove(query).Ok;
        }
        public IObservable<ParkingArea> Extract(IMongoQuery query)
        {
            return Observable.Create<ParkingArea>(async observer =>
            {
                var totalEntitiesToProcess  = serverProvider.Database.OsmCompoundQueryCount(query);
                var operationCounter        = new OperationCounter(log, string.Format("OSM Parking Area Extraction from {0}",query), totalEntitiesToProcess);
                var cursor                  = serverProvider.Database.OsmCompoundQuery(query);

                foreach (var entity in cursor)
                {
                    var entityContext   = new OsmEntityContext(serverProvider.Database, entity);
                    var parkingArea     = new ParkingArea() { Id = Guid.NewGuid(), Source = ParkingAreaSource.Maps, Confidence = configuration.Model.Confidence };
                    var isValid         = true;

                    foreach (var extractionRule in extractionRules)
                    {
                        var continueExtraction = await extractionRule.Extract(entityContext, parkingArea);

                        if (!continueExtraction)
                        {
                            log.Info("Entity {0} was dropped from extraction by rule {1}", entity, extractionRule.GetType().Name.Replace("Extraction", string.Empty).Replace("Rule", string.Empty));
                            isValid = false;
                            break;
                        }
                    }

                    if (isValid)
                    {
                        observer.OnNext(parkingArea);
                    }

                    operationCounter.Increment();
                }
            });
        }
        public static List<供应商> 抽选供应商(int count, IMongoQuery conditions, IEnumerable<long> selected, IEnumerable<long> avoid)
        {
            var ret = new List<供应商>(count);
            var rnd = new Random();

            conditions = conditions.And(Query<供应商>.EQ(o => o.审核数据.审核状态, 审核状态.审核通过));
            if (null != selected && 0 != selected.Count())
            {
                var q = Query.NotIn("_id", new BsonArray(selected));
                conditions = Query.And(conditions, q);
            }
            if (null != avoid && 0 != avoid.Count())
            {
                var 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<供应商>();
            var r = Mongo.查询<供应商>(0, 0, 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;
        }
        public static long OsmCompoundQueryCount(this MongoDatabase database,IMongoQuery query)
        {
            var r1 = database.GetOsmCollection(OsmEntityType.Node).FindAs<OsmNode>(query);
            var r2 = database.GetOsmCollection(OsmEntityType.Way).FindAs<OsmWay>(query);
            var r3 = database.GetOsmCollection(OsmEntityType.Relation).FindAs<OsmRelation>(query);

            return r1.Count() + r2.Count() + r3.Count();
        }
 // constructors
 internal MongoUpdateMessage(BsonBinaryWriterSettings writerSettings, string collectionFullName, bool checkUpdateDocument, UpdateFlags flags, IMongoQuery query, IMongoUpdate update)
     : base(MessageOpcode.Update, null, writerSettings)
 {
     this.collectionFullName = collectionFullName;
     this.checkUpdateDocument = checkUpdateDocument;
     this.flags = flags;
     this.query = query;
     this.update = update;
 }
Beispiel #8
0
 public static IEnumerable<新闻> 查询图片新闻(int skip, int limit, IMongoQuery conditions = null)
 {
     var q = Query.SizeGreaterThan("内容主体.图片", 0);
     if (conditions != null)
     {
         q = q.And(conditions);
     }
     return Mongo.查询<新闻>(skip, limit,q , true, null, false, false);
 }
Beispiel #9
0
        private ICollection<KeyValuePair<string, int>> GetPageViewsByUserAgent(IMongoQuery query)
        {
            var reduce = new BsonJavaScript("function(o, agg) { agg.count++; }");
            var results = DB.PageViews.Group(query, "UserAgent", new { count = 0 }.ToBsonDocument(), reduce, null).ToList();

            return results
                .ToKeyValuePairs(x => x["UserAgent"].AsString, x => x["count"].ToInt32())
                .OrderByDescending(kvp => kvp.Value)
                .ToList();
        }
 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;
 }
Beispiel #11
0
        public static IMongoQuery GeoQuery(MongoLocation loc, double prox, IMongoQuery query)
        {
            var locQuery = QueryConstants.GeoQuery(loc, prox);

            var q = new QueryDocument();
            q.AddRange(BsonDocument.Parse(locQuery.ToString()));
            if (query != null) q.AddRange(BsonDocument.Parse(query.ToString()));

            return q;
        }
 internal MongoDeleteMessage(
     MongoServer server,
     string collectionFullName,
     RemoveFlags flags,
     IMongoQuery query
 ) :
     base(server, MessageOpcode.Delete) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.query = query;
 }
 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) {
 }
Beispiel #14
0
 public void SetQuery(IMongoQuery mongoQuery)
 {
     if (this.MongoQuery != null)
     {
         this.MongoQuery = QueryBuilder.Query.And(this.MongoQuery, mongoQuery);
     }
     else
     {
         this.MongoQuery = mongoQuery;
     }
 }
 // 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 static IEnumerable<OsmEntity> OsmCompoundQuery(this MongoDatabase database,IMongoQuery query)
        {
            var r1 = database.GetOsmCollection(OsmEntityType.Node).FindAs<OsmNode>(query);
            var r2 = database.GetOsmCollection(OsmEntityType.Way).FindAs<OsmWay>(query);
            var r3 = database.GetOsmCollection(OsmEntityType.Relation).FindAs<OsmRelation>(query);

            PrepareCursorForBatchProcessing(r1);
            PrepareCursorForBatchProcessing(r2);
            PrepareCursorForBatchProcessing(r3);

            return r1.Cast<OsmEntity>().Concat(r2).Concat(r3);
        }
 internal MongoUpdateMessage(
     MongoConnection connection,
     string collectionFullName,
     UpdateFlags flags,
     IMongoQuery query,
     IMongoUpdate update
 ) :
     base(connection, MessageOpcode.Update) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.query = query;
     this.update = update;
 }
 public RemoveOperation(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings,
     WriteConcern writeConcern,
     IMongoQuery query,
     RemoveFlags flags)
     : base(databaseName, collectionName, readerSettings, writerSettings, writeConcern)
 {
     _query = query;
     _flags = flags;
 }
        protected IMongoQuery WrapQuery(IMongoQuery query, BsonDocument options, ReadPreference readPreference, bool forShardRouter)
        {
            BsonDocument formattedReadPreference = null;
            if (forShardRouter && readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary)
            {
                BsonArray tagSetsArray = null;
                if (readPreference.TagSets != null)
                {
                    tagSetsArray = new BsonArray();
                    foreach (var tagSet in readPreference.TagSets)
                    {
                        var tagSetDocument = new BsonDocument();
                        foreach (var tag in tagSet)
                        {
                            tagSetDocument.Add(tag.Name, tag.Value);
                        }
                        tagSetsArray.Add(tagSetDocument);
                    }
                }

                if (tagSetsArray != null || readPreference.ReadPreferenceMode != ReadPreferenceMode.SecondaryPreferred)
                {
                    formattedReadPreference = new BsonDocument
                    {
                        { "mode", MongoUtils.ToCamelCase(readPreference.ReadPreferenceMode.ToString()) },
                        { "tags", tagSetsArray, tagSetsArray != null } // optional
                    };
                }
            }

            if (options == null && formattedReadPreference == null)
            {
                return query;
            }
            else
            {
                var queryDocument = (query == null) ? (BsonValue)new BsonDocument() : BsonDocumentWrapper.Create(query);
                var wrappedQuery = new QueryDocument
                {
                    { "$query", queryDocument },
                    { "$readPreference", formattedReadPreference, formattedReadPreference != null }, // only if sending query to a mongos
                };
                if (options != null)
                {
                    wrappedQuery.Merge(options);
                }
                return wrappedQuery;
            }
        }
Beispiel #20
0
        public static List<专家> 抽选专家(int count, IMongoQuery conditions, IEnumerable<long> selected, IEnumerable<long> avoid, string 所属单位)
        {
            var ret = new List<专家>(count);
            var rnd = new Random();

            var now = DateTime.Now;
            //筛选条件,专家3个月内不能被同一单位抽取,一年内不能被同一单位抽取3次
            var querydate = Query.Where(
                        " function(){" +
                        " var count = obj.历史抽取信息." + 所属单位 + ".length;" +
                        " if (count == 0) return true;" +
                        " if (count >0 && count <3 && new Date(obj.历史抽取信息." + 所属单位 + "[count-1]) < new Date(\"" + now.AddMonths(-3).ToString() + "\")) return true;" +
                        " if (count >=3 &&  new Date(obj.历史抽取信息." + 所属单位 + "[count-1]) < new Date(\"" + now.AddMonths(-3).ToString() + "\") && new Date(obj.历史抽取信息." + 所属单位 + "[count-3]) < new Date(\"" + now.AddYears(-1).ToString() + "\")) return true;" +
                        " return false;" +
                        " }");
            var q = Query<专家>.EQ(o => o.审核数据.审核状态, 审核状态.审核通过).And(Query.NotExists("历史抽取信息." + 所属单位).Or(querydate));
            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<专家>();
            var r = Mongo.查询<专家>(0, 0, 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;
        }
Beispiel #21
0
        public bool Archive(IMongoQuery query, long userId)
        {
            if (query == null)
                throw new ArgumentNullException("Query must not be null");
            var collection = OriginServer.GetCurrentCollection();
            ArchiveServer.ChangeDatabase(collection.Database.Name, collection.Name);

            var result = false;
            var document = OriginServer.GetCurrentCollection().FindAndRemove(query, SortBy.Null).ModifiedDocument;
            if (document != null)
            {
                document["DeletedOn"] = DateTime.Now;
                document["DeletedBy"] = userId;
                ArchiveServer.GetCurrentCollection().Save(document);
            }
            return result;
        }
 public UpdateOperation(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings,
     WriteConcern writeConcern,
     IMongoQuery query,
     IMongoUpdate update,
     UpdateFlags flags,
     bool checkElementNames)
     : base(databaseName, collectionName, readerSettings, writerSettings, writeConcern)
 {
     _query = query;
     _update = update;
     _flags = flags;
     _checkElementNames = checkElementNames;
 }
 // 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 MongoUpdateMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     bool checkUpdateDocument,
     UpdateFlags flags,
     int maxDocumentSize,
     IMongoQuery query,
     IMongoUpdate update)
     : base(MessageOpcode.Update, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _checkUpdateDocument = checkUpdateDocument;
     _flags = flags;
     _maxDocumentSize = maxDocumentSize;
     _query = query;
     _update = update;
 }
 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;
 }
Beispiel #26
0
 /// <summary>
 /// 移除
 /// </summary>
 public static bool Remove(string collectionName, IMongoQuery query = null)
 {
     MongoCollection<BsonDocument> collection;
     MongoServer server = CreateMongoServer(collectionName, out collection);
     bool ok = false;
     try
     {
         ok = collection.Remove(query).Ok;
     }
     catch
     {
         ok = false;
     }
     //finally
     //{
     //    server.Disconnect();
     //}
     return ok;
 }
Beispiel #27
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;
        }
Beispiel #28
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;
        }
Beispiel #29
0
        private ICollection<KeyValuePair<DateTime, int>> GetPageViewsByDate(IMongoQuery query)
        {
            var map = new BsonJavaScript(
            @"function() {
            day = Date.UTC(this.ViewedAt.getFullYear(), this.ViewedAt.getMonth(), this.ViewedAt.getDate());
            emit({day: day, daynum: this.ViewedAt.getDate()}, {count: 1});
            }");

            var reduce = new BsonJavaScript(
            @"function(key, values) {
            var count = 0;
            values.forEach(function(v) {
            count += v['count'];
            });
            return {count: count};
            }");

            var results = DB.PageViews.MapReduce(query, map, reduce, MapReduceOptions.SetOutput(MapReduceOutput.Inline)).InlineResults.ToList();
            return results
                .ToKeyValuePairs(
                    x => DateTimeFromUnixTime(x["_id"].AsBsonDocument["day"].AsDouble),
                    x => x["value"].AsBsonDocument["count"].ToInt32())
                .OrderByDescending(kvp => kvp.Key).ToList();
        }
Beispiel #30
0
 /// <summary>
 /// 查找
 /// </summary>
 /// <param name="collectionName">表名</param>
 /// <param name="query">查找条件</param>
 /// <returns>查找的结果</returns>
 public static MongoCursor<BsonDocument> Search(string collectionName, IMongoQuery query = null)
 {
     MongoCollection<BsonDocument> collection;
     MongoServer server = CreateMongoServer(collectionName, out collection);
     if (server != null && collection != null)
     {
         try
         {
             return query == null ? collection.FindAll() : collection.Find(query);
         }
         catch
         {
             return null;
         }
         //finally
         //{
         //    server.Disconnect();
         //}
     }
     else
     {
         return null;
     }
 }
Beispiel #31
0
 public T FindAndModify <T>(IMongoQuery find, IMongoUpdate update)
 {
     return(db.GetCollection <T>().FindAndModify(find, SortBy.Ascending("_id"), update, true).GetModifiedDocumentAs <T>());
 }
Beispiel #32
0
 /// <summary>
 /// Injects a low level IMongoQuery into a LINQ where clause. Can only be used in LINQ queries.
 /// </summary>
 /// <param name="query">The low level query.</param>
 /// <returns>Throws an InvalidOperationException if called.</returns>
 public static bool Inject(this IMongoQuery query)
 {
     throw new InvalidOperationException("The LinqToMongo.Inject method is only intended to be used in LINQ Where clauses.");
 }
        public void TestTypeOfComparisonOnProperty()
        {
            IMongoQuery query = Query <TestClass> .Where(x => x.Prop.GetType() == typeof(B));

            Assert.Equal("{ \"Prop._t.0\" : { \"$exists\" : false }, \"Prop._t\" : \"B\" }", query.ToString());
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <param name="update">更新设置。调用示例:Update.Set("Title", "yanc") 或者 Update.Set("Title", "yanc").Set("Author", "yanc2") 等等</param>
 /// <returns></returns>
 public static WriteConcernResult UpdateAll <T>(string collectionName, IMongoQuery query, IMongoUpdate update)
 {
     return(UpdateAll <T>(ConnectionStringDefault, DatabaseDefault, collectionName, query, update));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="collectionName"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <returns></returns>
 public static WriteConcernResult DeleteAll(string collectionName, IMongoQuery query)
 {
     return(DeleteAll(ConnectionStringDefault, DatabaseDefault, collectionName, query));
 }
Beispiel #36
0
        public ICollection <Project> GetByNextSummaryNotificationOffset(byte hourToSendNotificationsAfterUtcMidnight, int limit = 10)
        {
            IMongoQuery query = Query.LT(FieldNames.NextSummaryEndOfDayTicks, new BsonInt64(DateTime.UtcNow.Ticks - (TimeSpan.TicksPerHour * hourToSendNotificationsAfterUtcMidnight)));

            return(Find <Project>(new MongoOptions().WithQuery(query).WithFields(FieldNames.Id, FieldNames.NextSummaryEndOfDayTicks).WithLimit(limit)));
        }
    // 根据查询条件,在table内查询结果
    public List <Dictionary <string, object> > ExecuteQuery(string table,              // 表名
                                                            IMongoQuery query,         // 查询条件,外部要自拼接
                                                            string[] fields  = null,
                                                            string sort      = "",
                                                            bool asc         = true,
                                                            int skip         = 0,
                                                            int limt         = 0,
                                                            string[] indexes = null)
    {
        // 没有设置条件时,返回全部数据
        if (query == null)
        {
            return(ExecuteGetAll(table, fields, sort, asc, skip, limt));
        }

        // 表不存在,直接返回
        if (!TableExists(table))
        {
            return(null);
        }

        List <Dictionary <string, object> > retlist = new List <Dictionary <string, object> >();

        try
        {
            var cb = check_table_keys(table, indexes);
            //IMongoQuery imq = Query.And(new IMongoQuery[]{Query.EQ(key, BsonValue.Create(val)),Query.NotExists(""),})

            var ret = cb.Find(query);

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

            if (sort != string.Empty)
            {
                if (asc)
                {
                    ret = ret.SetSortOrder(SortBy.Ascending(sort));
                }
                else
                {
                    ret = ret.SetSortOrder(SortBy.Descending(sort));
                }
            }

            if (skip > 0)
            {
                ret = ret.SetSkip(skip);
            }
            if (limt > 0)
            {
                ret = ret.SetLimit(limt);
            }

            var it = ret.GetEnumerator();

            while (it.MoveNext())
            {
                //if (it.Current.Contains("_id"))
                // it.Current.Remove("_id");
                retlist.Add(it.Current.ToDictionary());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            retlist.Clear();
        }
        return(retlist);
    }
 // 执行map-reduce
 public MapReduceResult executeMapReduce(string tablename, int serverid, int dbname, IMongoQuery query,
                                         string map_js, string reduce_js,
                                         string outTableName = "")
 {
     return(m_mongoServer[serverid].getDB(dbname).executeMapReduce(tablename, query, map_js, reduce_js, outTableName));
 }
    // 返回表tablename中满足条件的记录个数
    public long getRecordCount(string tablename, string fieldname, object val, int serverid, int dbid)
    {
        IMongoQuery imq = Query.EQ(fieldname, BsonValue.Create(val));

        return(getRecordCount(tablename, imq, serverid, dbid));
    }
    public List <BsonDocument> ExecuteQueryBsonDoc(string table,                 // 表名
                                                   IMongoQuery query,            // 查询条件,外部要自拼接
                                                   string[] fields  = null,
                                                   string sort      = "",
                                                   bool asc         = true,
                                                   int skip         = 0,
                                                   int limt         = 0,
                                                   string[] indexes = null)
    {
        // 表不存在,直接返回
        if (!TableExists(table))
        {
            return(null);
        }

        List <BsonDocument> retlist = new List <BsonDocument>();

        try
        {
            var cb = check_table_keys(table, indexes);
            MongoCursor <BsonDocument> ret = null;
            if (query == null)
            {
                ret = cb.FindAll();
            }
            else
            {
                ret = cb.Find(query);
            }

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

            if (sort != string.Empty)
            {
                if (asc)
                {
                    ret = ret.SetSortOrder(SortBy.Ascending(sort));
                }
                else
                {
                    ret = ret.SetSortOrder(SortBy.Descending(sort));
                }
            }

            if (skip > 0)
            {
                ret = ret.SetSkip(skip);
            }
            if (limt > 0)
            {
                ret = ret.SetLimit(limt);
            }

            var it = ret.GetEnumerator();

            while (it.MoveNext())
            {
                retlist.Add(it.Current);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            retlist.Clear();
        }
        return(retlist);
    }
Beispiel #41
0
        public static IMongoQuery Create <Info>(Info info)
        {
            var typeName = typeof(Info).Name;

            switch (typeName)
            {
            case "AppInfo":
            {
                return(Query.EQ("Key", new BsonString(Convert.ToString(info.GetPropertyValue("Key")))));
            }

            case "RoleInfo":
            {
                IMongoQuery query1 = Query.EQ("Code", new BsonString(Convert.ToString(info.GetPropertyValue("Code"))));
                return(Query.And(new IMongoQuery[] { query1 }));
            }

            case "RoleUserInfo":
            {
                IMongoQuery query1 = Query.EQ("RoleCode", new BsonString(Convert.ToString(info.GetPropertyValue("RoleCode"))));
                IMongoQuery query2 = Query.EQ("Account", new BsonString(Convert.ToString(info.GetPropertyValue("Account"))));
                return(Query.And(query1, query2));
            }

            case "RoleOrganizationInfo":
            {
                IMongoQuery query1 = Query.EQ("RoleCode", new BsonString(Convert.ToString(info.GetPropertyValue("RoleCode"))));
                IMongoQuery query2 = Query.EQ("OrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OrganizationCode"))));
                return(Query.And(query1, query2));
            }

            case "RolePositionInfo":
            {
                IMongoQuery query1 = Query.EQ("RoleCode", new BsonString(Convert.ToString(info.GetPropertyValue("RoleCode"))));
                IMongoQuery query2 = Query.EQ("OrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OrganizationCode"))));
                IMongoQuery query3 = Query.EQ("PositionCode", new BsonString(Convert.ToString(info.GetPropertyValue("PositionCode"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3 }));
            }

            case "RoleOperationInfo":
            {
                IMongoQuery query1 = Query.EQ("RoleCode", new BsonString(Convert.ToString(info.GetPropertyValue("RoleCode"))));
                IMongoQuery query2 = Query.EQ("AppKey", new BsonString(Convert.ToString(info.GetPropertyValue("AppKey"))));
                IMongoQuery query3 = Query.EQ("TargetCode", new BsonString(Convert.ToString(info.GetPropertyValue("TargetCode"))));
                IMongoQuery query4 = Query.EQ("OperationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OperationCode"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3, query4 }));
            }

            case "RoleMutexInfo":
            {
                IMongoQuery query1 = Query.EQ("Group", new BsonString(Convert.ToString(info.GetPropertyValue("Group"))));
                IMongoQuery query2 = Query.EQ("Type", new BsonInt32(Convert.ToInt32(info.GetPropertyValue("Type").ToString())));
                IMongoQuery query3 = Query.EQ("RoleCode", new BsonString(Convert.ToString(info.GetPropertyValue("RoleCode"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3 }));
            }

            case "UserInfo":
            {
                return(Query.EQ("Account", new BsonString(Convert.ToString(info.GetPropertyValue("Account")))));
            }

            case "UserStateInfo":
            {
                IMongoQuery query1 = Query.EQ("Account", new BsonString(Convert.ToString(info.GetPropertyValue("Account"))));
                IMongoQuery query2 = Query.EQ("DeviceId", new BsonString(Convert.ToString(info.GetPropertyValue("DeviceId"))));
                return(Query.And(query1, query2));
            }

            case "OrganizationInfo":
            {
                return(Query.EQ("Code", new BsonString(Convert.ToString(info.GetPropertyValue("Code")))));
            }

            case "TargetInfo":
            {
                IMongoQuery query1 = Query.EQ("AppKey", new BsonString(Convert.ToString(info.GetPropertyValue("AppKey"))));
                IMongoQuery query2 = Query.EQ("Code", new BsonString(Convert.ToString(info.GetPropertyValue("Code"))));
                return(Query.And(query1, query2));
            }

            case "OperationInfo":
            {
                IMongoQuery query1 = Query.EQ("AppKey", new BsonString(Convert.ToString(info.GetPropertyValue("AppKey"))));
                IMongoQuery query2 = Query.EQ("TargetCode", new BsonString(Convert.ToString(info.GetPropertyValue("TargetCode"))));
                IMongoQuery query3 = Query.EQ("Code", new BsonString(Convert.ToString(info.GetPropertyValue("Code"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3 }));
            }

            case "PositionInfo":
            {
                IMongoQuery query1 = Query.EQ("OrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OrganizationCode"))));
                IMongoQuery query2 = Query.EQ("Code", new BsonString(Convert.ToString(info.GetPropertyValue("Code"))));
                return(Query.And(new IMongoQuery[] { query1, query2 }));
            }

            case "PositionReportToInfo":
            {
                IMongoQuery query1 = Query.EQ("OrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OrganizationCode"))));
                IMongoQuery query2 = Query.EQ("PositionCode", new BsonString(Convert.ToString(info.GetPropertyValue("PositionCode"))));
                IMongoQuery query3 = Query.EQ("HigherOrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("HigherOrganizationCode"))));
                IMongoQuery query4 = Query.EQ("HigherPositionCode", new BsonString(Convert.ToString(info.GetPropertyValue("HigherPositionCode"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3 }));
            }

            case "PositionUserInfo":
            {
                IMongoQuery query1 = Query.EQ("OrganizationCode", new BsonString(Convert.ToString(info.GetPropertyValue("OrganizationCode"))));
                IMongoQuery query2 = Query.EQ("PositionCode", new BsonString(Convert.ToString(info.GetPropertyValue("PositionCode"))));
                IMongoQuery query3 = Query.EQ("Account", new BsonString(Convert.ToString(info.GetPropertyValue("Account"))));
                return(Query.And(new IMongoQuery[] { query1, query2, query3 }));
            }
            }
            return(null);
        }
Beispiel #42
0
 public void UpdateOne <T>(IMongoQuery find, IMongoUpdate update)
 {
     db.GetCollection <T>().Update(find, update);
 }
Beispiel #43
0
        /// <summary>
        ///     根据条件查询问题列表并且分页
        /// </summary>
        /// <param name="sortID">分类ID</param>
        ///  <param name="TenantId">公司ID</param>
        /// <param name="content">题目</param>
        /// <param name="type">类型</param>
        /// <param name="level">难度</param>
        /// <param name="key">知识点</param>
        /// <param name="pageSize">每页显示的条数</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="totalcount">总数</param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="open"></param>
        /// <param name="available"></param>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public List <TalQuestion> GetListByQuery(ref int totalcount, List <int> sortID, int TenantId, string content,
                                                 List <int> key,
                                                 int pageSize, int pageIndex, int type, int level, DateTime?start,
                                                 DateTime?end, int open = 99,
                                                 int available          = 99, int[] userIds = null)
        {
            var querylist = new List <IMongoQuery>();

            #region 当查询内容含有特殊字符时模糊查询有问题

            if (content != "")
            {
                querylist.Add(Query.Matches("QuestionContent", new BsonRegularExpression("" + content.FuzzyQuery() + "")));
            }

            #endregion

            if (key.Count != 0)
            {
                querylist.Add(Query.In("QuestionKey", new BsonArray(key)));
            }
            if (type != 0)
            {
                querylist.Add(Query.EQ("QuestionType", type));
            }
            if (level != 0)
            {
                querylist.Add(Query.EQ("QuestionLevel", level));
            }
            if (sortID.Count != 0)
            {
                querylist.Add(Query.In("QuestionSortID", new BsonArray(sortID)));
            }
            if (TenantId != -1)
            {
                querylist.Add(Query.EQ("TenantId", TenantId));
            }
            if (open != 99)
            {
                querylist.Add(Query.EQ("QuestionOpen", open));
            }
            if (available != 99)
            {
                querylist.Add(Query.EQ("QuestionAvailable", available));
            }
            if (userIds != null && userIds.Length > 0)
            {
                querylist.Add(Query.In("UserID", new BsonArray(userIds)));
            }
            if (start.HasValue)
            {
                querylist.Add(Query.GTE("LastUpdateTime", start.Value));
            }
            if (end.HasValue)
            {
                querylist.Add(Query.LTE("LastUpdateTime", end.Value));
            }
            //querylist.Add(Query.EQ("Status", 0));
            IMongoQuery qu = querylist.Count == 0 ? null : Query.And(querylist);
            return(GetAllList <TalQuestion>(ref totalcount, qu, new SortByDocument("_id", -1), pageIndex, pageSize));
        }
Beispiel #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoCursor"/> class.
 /// </summary>
 /// <param name="collection">The collection.</param>
 /// <param name="query">The query.</param>
 /// <param name="readConcern">The read concern.</param>
 /// <param name="readPreference">The read preference.</param>
 /// <param name="serializer">The serializer.</param>
 protected MongoCursor(MongoCollection collection, IMongoQuery query, ReadConcern readConcern, ReadPreference readPreference, IBsonSerializer serializer)
     : this(collection, query, readPreference, serializer)
 {
     _readConcern = readConcern;
 }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <returns></returns>
 public static T GetOne <T>(string collectionName, IMongoQuery query)
 {
     return(GetOne <T>(ConnectionStringDefault, DatabaseDefault, collectionName, query));
 }
Beispiel #46
0
        public static MongoCursor Create(Type documentType, MongoCollection collection, IMongoQuery query, ReadConcern readConcern, ReadPreference readPreference, IBsonSerializer serializer)
        {
            var cursorDefinition = typeof(MongoCursor <>);
            var cursorType       = cursorDefinition.MakeGenericType(documentType);
            var constructorInfo  = cursorType.GetTypeInfo().GetConstructor(new Type[] { typeof(MongoCollection), typeof(IMongoQuery), typeof(ReadConcern), typeof(ReadPreference), typeof(IBsonSerializer) });

            return((MongoCursor)constructorInfo.Invoke(new object[] { collection, query, readConcern, readPreference, serializer }));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static WriteConcernResult DeleteAll(string connectionString, string databaseName, string collectionName, IMongoQuery query)
        {
            var client = new MongoClient(connectionString);
            var server = client.GetServer();

            //获取数据库或者创建数据库(不存在的话)。
            MongoDatabase database = server.GetDatabase(databaseName);

            WriteConcernResult result;

            using (server.RequestStart(database))//开始连接数据库。
            {
                MongoCollection <BsonDocument> myCollection = database.GetCollection <BsonDocument>(collectionName);

                result = null == query?myCollection.RemoveAll() : myCollection.Remove(query);
            }
            return(result);
        }
Beispiel #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UpdateRequest"/> class.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="update">The update.</param>
 public UpdateRequest(IMongoQuery query, IMongoUpdate update)
     : base(WriteRequestType.Update)
 {
     _query  = query;
     _update = update;
 }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="update">更新设置。调用示例:Update.Set("Title", "yanc") 或者 Update.Set("Title", "yanc").Set("Author", "yanc2") 等等</param>
        /// <returns></returns>
        public static WriteConcernResult UpdateAll <T>(string connectionString, string databaseName, string collectionName, IMongoQuery query, IMongoUpdate update)
        {
            WriteConcernResult result;

            if (null == query || null == update)
            {
                return(null);
            }

            var client = new MongoClient(connectionString);
            var server = client.GetServer();

            //获取数据库或者创建数据库(不存在的话)。
            MongoDatabase database = server.GetDatabase(databaseName);

            using (server.RequestStart(database))//开始连接数据库。
            {
                MongoCollection <BsonDocument> myCollection = database.GetCollection <BsonDocument>(collectionName);

                result = myCollection.Update(query, update, UpdateFlags.Multi);
            }
            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
        /// <param name="pagerInfo"></param>
        /// <param name="sortBy">排序用的。调用示例:SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
        /// <param name="fields">只返回所需要的字段的数据。调用示例:"Title" 或者 new string[] { "Title", "Author" }等等</param>
        /// <returns></returns>
        public static List <T> GetAll <T>(string connectionString, string databaseName, string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, params string[] fields)
        {
            var client = new MongoClient(connectionString);
            var server = client.GetServer();

            //获取数据库或者创建数据库(不存在的话)。
            MongoDatabase database = server.GetDatabase(databaseName);

            var result = new List <T>();

            using (server.RequestStart(database))//开始连接数据库。
            {
                MongoCollection <BsonDocument> myCollection = database.GetCollection <BsonDocument>(collectionName);

                MongoCursor <T> myCursor;

                if (null == query)
                {
                    myCursor = myCollection.FindAllAs <T>();
                }
                else
                {
                    myCursor = myCollection.FindAs <T>(query);
                }

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

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

                foreach (T entity in myCursor.SetSkip((pagerInfo.Page - 1) * pagerInfo.PageSize).SetLimit(pagerInfo.PageSize))//.SetSkip(100).SetLimit(10)是指读取第一百条后的10条数据。
                {
                    result.Add(entity);
                }
            }
            return(result);
        }
Beispiel #51
0
 public ArticleData GetSingle(IMongoQuery <ArticleData> query)
 {
     return(GetMany(query).Single());
 }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <param name="pagerInfo"></param>
 /// <param name="sortBy">排序用的。调用示例:SortBy.Descending("Title") 或者 SortBy.Descending("Title").Ascending("Author")等等</param>
 /// <param name="fields">只返回所需要的字段的数据。调用示例:"Title" 或者 new string[] { "Title", "Author" }等等</param>
 /// <returns></returns>
 public static List <T> GetAll <T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo, IMongoSortBy sortBy, params string[] fields)
 {
     return(GetAll <T>(ConnectionStringDefault, DatabaseDefault, collectionName, query, pagerInfo, sortBy, fields));
 }
        public void TestTypeIsOnProperty()
        {
            IMongoQuery query = Query <TestClass> .Where(x => x.Prop is B);

            Assert.Equal("{ \"Prop._t\" : \"B\" }", query.ToString());
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <param name="pagerInfo"></param>
 /// <returns></returns>
 public static List <T> GetAll <T>(string collectionName, IMongoQuery query, PagerInfo pagerInfo)
 {
     return(GetAll <T>(ConnectionStringDefault, DatabaseDefault, collectionName, query, pagerInfo, null));
 }
Beispiel #55
0
 // public static methods
 /// <summary>
 /// Returns the first matching element in the array specified by name.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="query">The query.</param>
 /// <returns>The build (so method calls can be chained).</returns>
 public static FieldsBuilder ElemMatch(string name, IMongoQuery query)
 {
     return(new FieldsBuilder().ElemMatch(name, query));
 }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="count"></param>
 /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
 /// <returns></returns>
 public static List <T> GetAll <T>(string collectionName, int count, IMongoQuery query)
 {
     return(GetAll <T>(collectionName, count, query, null));
 }
Beispiel #57
0
 public MongoCursor <T> Find <T>(IMongoQuery find)
 {
     return(db.GetCollection <T>().Find(find));
 }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="query">条件查询。 调用示例:Query.Matches("Title", "女神") 或者 Query.EQ("Title", "女神") 或者Query.And(Query.Matches("Title", "女神"),Query.EQ("Author", "yanc")) 等等</param>
        /// <returns></returns>
        public static T GetOne <T>(string connectionString, string databaseName, string collectionName, IMongoQuery query)
        {
            var client = new MongoClient(connectionString);
            var server = client.GetServer();

            //获取数据库或者创建数据库(不存在的话)。
            MongoDatabase database = server.GetDatabase(databaseName);

            T result;

            using (server.RequestStart(database))//开始连接数据库。
            {
                MongoCollection <BsonDocument> myCollection = database.GetCollection <BsonDocument>(collectionName);

                result = null == query?myCollection.FindOneAs <T>() : myCollection.FindOneAs <T>(query);
            }
            return(result);
        }
 // 取得表tablename中, 字段名fieldname 为value行
 public Dictionary <string, object> getTableData(string tablename, int serverid, int dbid, IMongoQuery query, string[] fields = null)
 {
     try
     {
         return(m_mongoServer[serverid].getDB(dbid).ExecuteGetByQuery(tablename, query, fields));
     }
     catch (System.Exception ex)
     {
         LOGW.Info(ex.ToString());
     }
     return(null);
 }
Beispiel #60
0
        /// <summary>
        /// Returns all features within a bounding box
        /// </summary>
        /// <param name="classIndex">Ignore - Feature Datasets unsupported</param>
        /// <param name="env">The bounding box used for searching</param>
        /// <param name="strictSearch">Ignore</param>
        /// <param name="whereClause">Currently unsupported</param>
        /// <param name="fieldMap">Which fields are included in results</param>
        /// <returns></returns>
        public IPlugInCursorHelper FetchByEnvelope(int classIndex, IEnvelope env, bool strictSearch, string whereClause, object fieldMap)
        {
            IMongoQuery conditions = null;

            return(new MongoDBCursor(m_Connection[m_Entry.Name], env, conditions, CommonConst.SHAPEFIELD, (System.Array)fieldMap, m_Entry.Fields));
        }