public object GetContactTypeLookUps(ContactLookUpGroupType type) { var dataResponse = new List <MEContactTypeLookup>(); using (var ctx = new ContactTypeLookUpMongoContext(_dbName)) { var queries = new List <IMongoQuery> { Query <MEContactTypeLookup> .EQ(c => c.Active, true), Query <MEContactTypeLookup> .EQ(c => c.DeleteFlag, false) }; if (type != ContactLookUpGroupType.Unknown) { var typeMongoQuery = Query <MEContactTypeLookup> .EQ(c => c.GroupId, type); queries.Add(typeMongoQuery); } var query = Query.And(queries); var sortBy = new SortByBuilder <MEContactTypeLookup>().Ascending(c => c.Name); var lookUps = ctx.ContactTypeLookUps.Collection.Find(query); dataResponse = lookUps.SetSortOrder(sortBy).ToList(); } return(dataResponse); }
public static SortByBuilder BuildSortByBuilder(string sortbyExpression) { try { // create sort order builder SortByBuilder builder = new SortByBuilder(); string[] splitSortExpr = sortbyExpression.Split(','); foreach (string s in splitSortExpr) { string[] splitSort = s.Split(':'); if (splitSort[1].Equals("1")) { builder.Ascending(new string[] { splitSort[0].ToString() }); } else { builder.Descending(new string[] { splitSort[0].ToString() }); } } return(builder); } catch (Exception) { throw; } }
public async Task <ContentResult> LatestTestResult() { var mongoconnection = ConfigurationManager.AppSettings["mongo"]; var database = ConfigurationManager.AppSettings["mongodb"]; var mongoClient = new MongoClient(mongoconnection); var server = mongoClient.GetServer(); server.Connect(); var db = server.GetDatabase(database); var collection = db.GetCollection("testresults"); var query = new SortByBuilder(); query.Descending("Timestamp"); var latestDocument = collection.FindAllAs <BsonDocument>().SetSortOrder(query).SetLimit(1); server.Disconnect(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; var json = latestDocument.ToJson(jsonWriterSettings); return(Content(json, "application/json")); }
/// <summary> /// 获得排序 /// </summary> /// <returns></returns> public static SortByBuilder GetSort(List <DataFilter.QueryFieldItem> FieldItemLst) { var sort = new SortByBuilder(); List <String> ascendingList = new List <String>(); List <String> descendingList = new List <String>(); //_id将以文字的形式排序,所以不要排序_id!! foreach (var item in FieldItemLst) { switch (item.sortType) { case DataFilter.SortType.NoSort: break; case DataFilter.SortType.Ascending: ascendingList.Add(item.ColName); break; case DataFilter.SortType.Descending: descendingList.Add(item.ColName); break; default: break; } } sort.Ascending(ascendingList.ToArray()); sort.Descending(descendingList.ToArray()); return(sort); }
/// <summary> /// 获得排序 /// </summary> /// <returns></returns> public static SortByBuilder GetSort(List <DataFilter.QueryFieldItem> fieldItemLst) { var sort = new SortByBuilder(); //排序 fieldItemLst.Sort((x, y) => { return(x.SortOrder - y.SortOrder); }); foreach (var item in fieldItemLst) { if (item.SortOrder == 0) { continue; } switch (item.SortType) { case DataFilter.SortType.NoSort: break; case DataFilter.SortType.Ascending: sort.Ascending(item.ColName); break; case DataFilter.SortType.Descending: sort.Descending(item.ColName); break; } } return(sort); }
/// <summary> /// </summary> /// <returns></returns> public static SortByBuilder GetSort(List <DataFilter.QueryFieldItem> fieldItemLst) { var sort = new SortByBuilder(); var ascendingList = new List <string>(); var descendingList = new List <string>(); foreach (var item in fieldItemLst) { switch (item.SortType) { case DataFilter.SortType.NoSort: break; case DataFilter.SortType.Ascending: ascendingList.Add(item.ColName); break; case DataFilter.SortType.Descending: descendingList.Add(item.ColName); break; } } sort.Ascending(ascendingList.ToArray()); sort.Descending(descendingList.ToArray()); return(sort); }
public TGEula GetLatest() { IMongoQuery query = MongoQueryHelper.GetQuery(); IMongoSortBy sortBy = new SortByBuilder().Descending("LastModifiedDateTime"); MongoCursor cursor = MongoCollection.Find(query).SetSortOrder(sortBy); return(GetOneItem <TGEula>(cursor)); }
public List <Match> GetRecentMatches(int numberOfMatches) { var sbb = new SortByBuilder(); sbb.Descending("TimeStampUtc"); var matches = Collection.FindAllAs <Match>().SetSortOrder(sbb).SetLimit(numberOfMatches).ToList(); return(matches); }
public IEnumerable <IEnumerable <KeyValuePair <string, object> > > Find(string entityName, QueryObject query, QuerySortObject[] sort, int?skip, int?limit) { var mongoCollection = MongoStaticContext.Context.GetBsonCollection(RECORD_COLLECTION_PREFIX + entityName); var mongoQuery = ConvertQuery(query); var cursor = mongoCollection.Find(mongoQuery); if (sort != null && sort.Length > 0) { SortByBuilder sortBy = null; foreach (var s in sort) { if (s.SortType == QuerySortType.Ascending) { sortBy = sortBy == null?SortBy.Ascending(s.FieldName) : sortBy.Ascending(s.FieldName); } else { sortBy = sortBy == null?SortBy.Descending(s.FieldName) : sortBy.Descending(s.FieldName); } } cursor.SetSortOrder(sortBy); } if (skip.HasValue) { cursor.SetSkip(skip.Value); } if (limit.HasValue) { cursor.SetLimit(limit.Value); } List <List <KeyValuePair <string, object> > > result = new List <List <KeyValuePair <string, object> > >(); foreach (BsonDocument doc in cursor) { List <KeyValuePair <string, object> > record = new List <KeyValuePair <string, object> >(); foreach (var fieldName in doc.Names) { if (fieldName == "_id") { record.Add(new KeyValuePair <string, object>("id", BsonTypeMapper.MapToDotNetValue(doc["_id"]))); } else { record.Add(new KeyValuePair <string, object>(fieldName, ConvertBsonValueToObject(doc[fieldName]))); } } result.Add(record); } return(result); }
public MongoSortWarpper Desc(params string[] keys) { if (MongoSortBy == null) { MongoSortBy = SortBy.Descending(keys); } else { MongoSortBy = MongoSortBy.Descending(keys); } return(this); }
/// <summary> /// 分页获取MongoDB数据 /// </summary> /// <param name="cultureID"></param> /// <param name="spuID"></param> /// <returns></returns> private static List <MongoDBSpuItemModel> Select(int cultureID, int spuID) { List <IMongoQuery> queryList = new List <IMongoQuery>(); queryList.Add(Query <MongoDBSpuItemModel> .GT(item => item.SPUID, spuID)); queryList.Add(Query <MongoDBSpuItemModel> .EQ(item => item.CultureID, cultureID)); IMongoQuery query = Query.And(queryList); queryList.Clear(); queryList = null; SortByBuilder <MongoDBSpuItemModel> sort = SortBy <MongoDBSpuItemModel> .Ascending(item => item.SPUID); return(MongoDBHelper.Select <MongoDBSpuItemModel>(PAGE_SIZE, query, sort) ?? new List <MongoDBSpuItemModel>(0)); }
/// <summary> /// Appends a descending sort stage to the pipeline. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">The source.</param> /// <param name="field">The field to sort by.</param> /// <returns>The fluent aggregate interface.</returns> public static IOrderedAggregateFluent <TDocument, TResult> SortByDescending <TDocument, TResult>(this IAggregateFluent <TDocument, TResult> source, Expression <Func <TResult, object> > field) { Ensure.IsNotNull(source, "source"); Ensure.IsNotNull(field, "field"); var helper = new BsonSerializationInfoHelper(); helper.RegisterExpressionSerializer(field.Parameters[0], source.Collection.Settings.SerializerRegistry.GetSerializer <TResult>()); var sortDocument = new SortByBuilder <TResult>(helper).Descending(field).ToBsonDocument(); source = source.Sort(sortDocument); return(new AggregateFluent <TDocument, TResult>(source.Collection, source.Pipeline, source.Options, source.ResultSerializer)); }
protected virtual IMongoSortBy BuildSortExpression(TFilter filter) { IMongoSortBy sort = SortBy.Null; if (filter.Ordering.Any()) { var builder = new SortByBuilder(); foreach (var order in filter.Ordering) { builder = order.Desc ? builder.Descending(order.Key) : builder.Ascending(order.Key); } sort = builder; } return(sort); }
private static SortByBuilder GetSortOrder(IEnumerable <string> sortBy) { var builder = new SortByBuilder(); foreach (var field in sortBy) { if (field[0] == '-') { builder.Descending(field.Substring(1)); } else { builder.Ascending(field); } } return(builder); }
public void BufferedLogsRecordedTest() { Log.Info("a log 1"); Log.Info("a log 2"); Log.Info("a log 3"); Log.Info("a log 4"); Log.Info("a log 5"); SortByBuilder sbb = new SortByBuilder(); sbb.Descending("_id"); var allDocs = collection.FindAllAs <BsonDocument>().SetSortOrder(sbb).SetLimit(5); BsonDocument doc = allDocs.First(); Assert.AreEqual(doc.GetElement("message").Value.AsString, "a log 5"); }
/// <summary> /// Modifies the current sort stage by appending a descending field specification to it. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">The source.</param> /// <param name="field">The field to sort by.</param> /// <returns>The fluent aggregate interface.</returns> public static IOrderedAggregateFluent <TDocument, TResult> ThenByDescending <TDocument, TResult>(this IOrderedAggregateFluent <TDocument, TResult> source, Expression <Func <TResult, object> > field) { Ensure.IsNotNull(source, "source"); Ensure.IsNotNull(field, "field"); var helper = new BsonSerializationInfoHelper(); helper.RegisterExpressionSerializer(field.Parameters[0], source.Collection.Settings.SerializerRegistry.GetSerializer <TResult>()); var sortDocument = new SortByBuilder <TResult>(helper).Descending(field).ToBsonDocument(); // this looks sketchy, but if we get here and this isn't true, then // someone is being a bad citizen. var currentSortStage = (BsonDocument)source.Pipeline.Last(); currentSortStage["$sort"].AsBsonDocument.AddRange(sortDocument); return(source); }
/// <summary> /// Converts PS objects to a SortBy object. /// </summary> /// <param name="values">Strings or @{Name=Boolean}. Null and empty is allowed.</param> /// <returns>SortBy object, may be empty but not null.</returns> public static IMongoSortBy ObjectsToSortBy(IEnumerable values) { if (values == null) { return(SortBy.Null); } var builder = new SortByBuilder(); foreach (var it in values) { var name = it as string; if (name != null) { builder.Ascending(name); continue; } var hash = it as IDictionary; if (hash == null) { throw new ArgumentException("SortBy: Invalid size object type."); } if (hash.Count != 1) { throw new ArgumentException("SortBy: Expected a dictionary with one entry."); } foreach (DictionaryEntry kv in hash) { name = kv.Key.ToString(); if (LanguagePrimitives.IsTrue(kv.Value)) { builder.Ascending(name); } else { builder.Descending(name); } } } return(builder); }
public static SortByBuilder GetSort(TaskQueue.TQItemSelector selector) { SortByBuilder sb = new SortByBuilder(); foreach (KeyValuePair <string, TaskQueue.TQItemSelectorParam> kv in selector.parameters) { switch (kv.Value.ValueSet) { case TaskQueue.TQItemSelectorSet.Ascending: sb = sb.Ascending(kv.Key); break; case TaskQueue.TQItemSelectorSet.Descending: sb = sb.Descending(kv.Key); break; } } return(sb); }
private void ConnectBtn_Click(object sender, EventArgs e) { try { mongo = new MongoDBHelper(DbAddressTxt.Text + ":" + PortTxt.Text, DbNameTxt.Text, CollectionNameTxt.Text); } catch (FormatException) { MessageBox.Show("Please Make Sure All Fields Entered Correctly", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } SortByBuilder sbb = new SortByBuilder(); sbb.Descending("_id"); var lastDocs = mongo.collection.FindAllAs <BsonDocument>().SetSortOrder(sbb).SetLimit(15); ArrayList keyList = new ArrayList(); foreach (BsonDocument lastDoc in lastDocs) { BsonObjectId id = lastDoc["_id"].AsObjectId; BsonDocument testRun = lastDoc["TestRun"].AsBsonDocument; string testRunName = testRun["@testRunName"].AsString; string userName = testRun["@userName"].AsString; string timeStamp = testRun["@timeStamp"].AsString; string hashtableKey = @"""" + testRunName + @""" """ + userName + @""" """ + timeStamp + @""""; //Track the order of each test run keyList.Add(hashtableKey); } for (int i = 0; i < keyList.Count; i++) { TestRunComboBox.Items.Insert(i, keyList[i]); CompareTestComboBox.Items.Insert(i, keyList[i]); //temporary to fill box BaseComboBox.Items.Insert(i, keyList[i]); } ReadyLbl.Text = "Connection Successful"; GetTestRunBtn.Enabled = true; GetDataByDaysBtn.Enabled = true; CompareSubmitBtn.Enabled = true; //add logic to focus depending on selected tab TestRunComboBox.Focus(); }
public void LogExceptionRecorded() { try { throw new ApplicationException("BOOM"); } catch (Exception e) { Log.Fatal("a log", e); } SortByBuilder sbb = new SortByBuilder(); sbb.Descending("_id"); var allDocs = collection.FindAllAs <BsonDocument>().SetSortOrder(sbb).SetLimit(1); BsonDocument doc = allDocs.First(); Assert.IsTrue(doc.GetElement("exception").Value is BsonString); Assert.IsTrue(doc.GetElement("exception").Value.AsString.IndexOf("BOOM", StringComparison.Ordinal) > -1); }
public static SortByBuilder GetSortByBuilder(string sort, Type entityType) { //sorting logic //sort - expecting a property name of the mongo entity, prefixed by sort direction +/- (= ascending / descending ) + is default. // for multiple sort fields ',' is the separator between sort properties expressions <+/-><Field1>,<+/-><Field2>, ... // examples: for entity METoDo: // +DueDate // -DueDate,-title //entityType - expecting the mongo entity type. for example: typeof(METoDo) string[] sortExpressions = sort != null?sort.Split(',') : new string[] { }; SortByBuilder sortBy = new SortByBuilder(); string sortByProperty; string sortDirection; string dbSortByField; if (sortExpressions.Length > 0) { foreach (string sortExpression in sortExpressions) { sortByProperty = GetSortByProperty(sortExpression); sortDirection = GetSortDirection(sortExpression); //get a string of the mongo property db name to sort by dbSortByField = GetSortByDbFieldName(sortByProperty, entityType); sortBy = AddSorting(sortBy, sortDirection, dbSortByField); } } else { dbSortByField = GetDefaultSortByDbFieldName(entityType); sortDirection = GetSortDirection(dbSortByField); // +/- dbSortByField = GetSortByProperty(dbSortByField); // cleaned database prop sortBy = AddSorting(sortBy, sortDirection, dbSortByField); } return(sortBy); }
private static SortByBuilder AddSorting(SortByBuilder sortBy, string sortDirection, string dbSortField) { //SortByBuilder sortBy; switch (sortDirection) { case "+": { sortBy = sortBy.Ascending(dbSortField); } break; case "-": { sortBy = sortBy.Descending(dbSortField); } break; default: sortBy = sortBy.Ascending(dbSortField); break; } return(sortBy); }
public List <T> Page <T>(DbQueryParams qParams) where T : class, new() { // First query part consists of search params with specified operator between List <IMongoQuery> queries = new List <IMongoQuery>(); foreach (var item in qParams.QueryParams) { queries.Add(Query.Matches(item.Key, new BsonRegularExpression(String.Format("(?:{0})", item.Value), "is"))); } var query = qParams.Operator == QueryOperator.AND ? Query.And(queries) : Query.Or(queries); MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).Find(query); cursor.SetSkip(qParams.SkipRecords).SetLimit(qParams.Count); // Setting the Sort params if (qParams.SortParams != null && qParams.SortParams.Count > 0) { SortByBuilder sbb = new SortByBuilder(); foreach (KeyValuePair <string, bool> sortItem in qParams.SortParams) { if (sortItem.Value) { sbb.Ascending(sortItem.Key); } else { sbb.Descending(sortItem.Key); } } cursor.SetSortOrder(sbb); } return(cursor.ToList()); }
private void ApplySorting(MongoCursor <BsonDocument> cursor, IEnumerable <SimpleOrderByItem> orderings) { if (orderings == null || !orderings.Any()) { return; } var sortBuilder = new SortByBuilder(); foreach (var ordering in orderings) { var name = ExpressionFormatter.GetFullName(ordering.Reference); if (ordering.Direction == OrderByDirection.Ascending) { sortBuilder.Ascending(name); } else { sortBuilder.Descending(name); } } cursor.SetSortOrder(sortBuilder); }
public virtual object Execute() { var visitor = new MongoDBVisitor(); visitor.Visite(ContentQuery.Expression); var mongoCursor = Query(visitor); if (mongoCursor == null) { return(DefaultValueExecute(visitor.CallType)); } if (visitor.Skip != 0) { mongoCursor.Skip = visitor.Skip; } SortByBuilder sortBuilder = new SortByBuilder(); foreach (var item in visitor.OrderFields) { if (item.Descending) { sortBuilder.Descending(item.FieldName); } else { sortBuilder.Ascending(item.FieldName); } } mongoCursor = mongoCursor.SetSortOrder(sortBuilder); object result = null; switch (visitor.CallType) { case Kooboo.CMS.Content.Query.Expressions.CallType.Count: result = Convert.ToInt32(mongoCursor.Count()); break; case Kooboo.CMS.Content.Query.Expressions.CallType.First: result = mongoCursor.First().ToContent(); break; case Kooboo.CMS.Content.Query.Expressions.CallType.Last: result = mongoCursor.Last().ToContent(); break; case Kooboo.CMS.Content.Query.Expressions.CallType.LastOrDefault: result = mongoCursor.Last().ToContent(); break; case Kooboo.CMS.Content.Query.Expressions.CallType.FirstOrDefault: result = mongoCursor.FirstOrDefault().ToContent(); break; case Kooboo.CMS.Content.Query.Expressions.CallType.Unspecified: default: if (visitor.Take != 0) { result = mongoCursor.Take(visitor.Take).Select(it => it.ToContent()); } else { result = mongoCursor.Select(it => it.ToContent()); } break; } if (mongoCursor.Database.Server.State != MongoServerState.Disconnected) { mongoCursor.Database.Server.Disconnect(); } return(result); }
public GetToDosDataResponse FindToDos(object request) { GetToDosDataResponse response = new GetToDosDataResponse(); List <ToDoData> todoList = null; GetToDosDataRequest dataRequest = (GetToDosDataRequest)request; try { using (SchedulingMongoContext ctx = new SchedulingMongoContext(_dbName)) { List <IMongoQuery> queries = new List <IMongoQuery>(); queries.Add(Query.EQ(METoDo.DeleteFlagProperty, false)); if (!string.IsNullOrEmpty(dataRequest.AssignedToId)) { ObjectId ato; if (ObjectId.TryParse(dataRequest.AssignedToId, out ato)) { queries.Add(Query.EQ(METoDo.AssignedToProperty, ato)); } else { // Fix for bug - ENG-1068, UI sends AssignedToId = -1 to query on all unassigned ToDos. if (string.Compare(dataRequest.AssignedToId, "-1", true) == 0) { //queries.Add(Query.Or(Query.EQ(METoDo.AssignedToProperty, BsonNull.Value), Query.EQ(METoDo.AssignedToProperty, BsonString.Empty))); queries.Add(Query.In(METoDo.AssignedToProperty, new BsonArray { BsonNull.Value, BsonString.Empty })); } } } if (!string.IsNullOrEmpty(dataRequest.NotAssignedToId)) { ObjectId nto; if (ObjectId.TryParse(dataRequest.NotAssignedToId, out nto)) { queries.Add(Query.NotIn(METoDo.AssignedToProperty, new BsonArray { nto, BsonNull.Value, BsonString.Empty })); } } if (!string.IsNullOrEmpty(dataRequest.CreatedById)) { queries.Add(Query.EQ(METoDo.RecordCreatedByProperty, ObjectId.Parse(dataRequest.CreatedById))); } if (!string.IsNullOrEmpty(dataRequest.PatientId)) { queries.Add(Query.EQ(METoDo.PatientIdProperty, ObjectId.Parse(dataRequest.PatientId))); } if (dataRequest.StatusIds != null && dataRequest.StatusIds.Count > 0) { queries.Add(Query.In(METoDo.StatusProperty, new BsonArray(dataRequest.StatusIds))); } if (dataRequest.PriorityIds != null && dataRequest.PriorityIds.Count > 0) { queries.Add(Query.In(METoDo.PriorityProperty, new BsonArray(dataRequest.PriorityIds))); //integer values (not object ids) } if (dataRequest.CategoryIds != null && dataRequest.CategoryIds.Count > 0) { List <BsonValue> categories = new List <BsonValue>(); foreach (string categoryId in dataRequest.CategoryIds) { if (categoryId.Length > 0) { categories.Add(BsonValue.Create(ObjectId.Parse(categoryId))); } else { categories.Add(BsonNull.Value); //empty string => include null categories ( not set ) } } queries.Add(Query.In(METoDo.CatgegoryProperty, categories)); } if (dataRequest.FromDate != null) { queries.Add(Query.GTE(METoDo.ClosedDateProperty, dataRequest.FromDate)); } IMongoQuery mQuery = Query.And(queries); MongoCursor <METoDo> cToDos = ctx.ToDos.Collection.Find(mQuery); List <METoDo> meToDos = null; SortByBuilder sortBy = MongoSortingUtils.GetSortByBuilder(dataRequest.Sort, typeof(METoDo)); cToDos = cToDos.SetSortOrder(sortBy); cToDos = (MongoCursor <METoDo>)MongoSortingUtils.ApplySkipTake(cToDos, dataRequest); response.TotalCount = cToDos.Count(); meToDos = cToDos.ToList(); //query now if (meToDos != null && meToDos.Count > 0) { todoList = new List <ToDoData>(); foreach (METoDo t in meToDos) { todoList.Add(new ToDoData { AssignedToId = t.AssignedToId == null ? string.Empty : t.AssignedToId.ToString(), CategoryId = t.Category == null ? string.Empty : t.Category.ToString(), ClosedDate = t.ClosedDate, CreatedById = t.RecordCreatedBy.ToString(), CreatedOn = t.RecordCreatedOn, Description = t.Description, DueDate = t.DueDate, StartTime = t.StartTime, Duration = t.Duration, Id = t.Id.ToString(), PatientId = t.PatientId == null ? string.Empty : t.PatientId.ToString(), PriorityId = (int)t.Priority, ProgramIds = Helper.ConvertToStringList(t.ProgramIds), StatusId = (int)t.Status, Title = t.Title, UpdatedOn = t.LastUpdatedOn, DeleteFlag = t.DeleteFlag, ExternalRecordId = t.ExternalRecordId, SourceId = t.SourceId.ToString() }); } } } response.ToDos = todoList; return(response); } catch (Exception ex) { throw new Exception("DD:MongoToDoRepository:FindToDos()::" + ex.Message, ex.InnerException); } }
public List <CounterSeriesData> GetCounterData(DateTime beginDate, DateTime endDate, int counterCategoryId, int counterNameId, int counterSourceId, int counterInstanceId, int counterExtDataId, List <string> seriesFilter) { List <CounterSeriesData> resultData = new List <CounterSeriesData>(); if (seriesFilter.Count == 0) { return(resultData); } bool getAllSeries = seriesFilter.Contains("*"); List <string> seriesNames = new List <string>(); MongoCollection <BsonDocument> items = Database.GetCollection("countersData"); string mappedCategoryName = CountersMapper.GetMappedCategoryName(counterCategoryId); string mappedCounterName = CountersMapper.GetMappedCounterName(counterCategoryId, counterNameId); string mappedCounterInstance = CountersMapper.GetMappedCounterInstanceName(counterCategoryId, counterNameId, counterInstanceId); string mappedCounterSource = CountersMapper.GetMappedCounterSourceName(counterCategoryId, counterNameId, counterSourceId); string mappedCounterExtData = CountersMapper.GetMappedCounterExtDataName(counterCategoryId, counterNameId, counterExtDataId); QueryComplete qb = beginDate == endDate ? Query.EQ("date", beginDate) : Query.GT("date", beginDate).LTE(endDate); QueryComplete qb2 = Query.EQ("counterCategory", mappedCategoryName); QueryComplete qb3 = Query.EQ("counterName", mappedCounterName); SortByBuilder sortOrder = new SortByBuilder().Ascending("date"); var cursor = items.Find(Query.And(qb, qb2, qb3)); cursor.SetSortOrder(sortOrder); string counterDescription = counterSourceId + "/" + counterInstanceId + "/" + counterExtDataId; cursor.SetFields(Fields.Include("type", "date", "data." + counterDescription)); foreach (BsonDocument cnt in cursor) { var dateTime = cnt["date"].AsDateTime; var countersData = cnt["data"].AsBsonDocument; if (!countersData.Contains(counterDescription)) { foreach (string seriesName in seriesNames) { if (getAllSeries || seriesFilter.Contains(seriesName)) { resultData.Find(f => f.SeriesName == seriesName).AddSeriesPoint(new SeriesPoint(dateTime, null)); } } continue; } var seriesPoints = countersData[counterDescription].AsBsonDocument; foreach (BsonElement seriesPoint in seriesPoints) { string seriesName = seriesPoint.Name; if (!seriesNames.Contains(seriesName)) { seriesNames.Add(seriesName); } if (!getAllSeries && !seriesFilter.Contains(seriesName)) { continue; } var value = seriesPoint.Value.IsString ? new UniversalValue( TimeSpan.Parse(seriesPoint.Value.AsString)) : new UniversalValue( seriesPoint.Value.ToDouble()); var a = resultData.Find(f => f.SeriesName == seriesName); if (a == null) { a = new CounterSeriesData(seriesName, value.Type, mappedCategoryName, mappedCounterName, mappedCounterSource, mappedCounterInstance, mappedCounterExtData); resultData.Add(a); } a.AddSeriesPoint(new SeriesPoint(dateTime, value)); } } return(resultData); }
public List <PatientData> Select(string query, string[] filterData, string querySort, int skip, int take) { #region commented code /* Query without filter: * { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}} * * Query with single field filter: * { $and : [ * { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}}, * { $or : [ * { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'FN'}}}, * { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'LN'}}}, * { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'PN'}}} * ] * } * ] * } * * Query with double field filter: * { $and : [ * { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}}, * { $and : [ * { $or : [ * { sf : { $elemMatch: {'val':/^<First Field Text Here>/i, 'fldn':'FN'}}}, * { sf : { $elemMatch: {'val':/^<First Field Text Here>/i, 'fldn':'PN'}}} * ] * }, * { sf: { $elemMatch : {'val':/^<Second Field Text Here>/i, 'fldn':'LN'}}} * ] * } * ] * } * */ #endregion try { string jsonQuery = string.Empty; string queryName = "TBD"; //Pass this into the method call string redisKey = string.Empty; if (filterData[0].Trim() == string.Empty) { jsonQuery = query; redisKey = string.Format("{0}{1}{2}", queryName, skip, take); } else { if (filterData[1].Trim() == string.Empty) { redisKey = string.Format("{0}{1}{2}{3}", queryName, filterData[0].Trim(), skip, take); jsonQuery = "{ $and : [ "; jsonQuery += string.Format("{0}, ", query); jsonQuery += "{ $or : [ "; jsonQuery += "{ sf: { $elemMatch : {'val':/^"; jsonQuery += string.Format("{0}/i, ", filterData[0].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'FN'}}}, "; jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^"; jsonQuery += string.Format("{0}/i, ", filterData[0].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'LN'}}}, "; jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^"; jsonQuery += string.Format("{0}/i, ", filterData[0].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'PN'}}}]}]}"; } else { redisKey = string.Format("{0}{1}{2}{3}{4}", queryName, filterData[0].Trim(), filterData[1].Trim(), skip, take); jsonQuery = "{ $and : [ "; jsonQuery += string.Format("{0}, ", query); jsonQuery += "{ $and : [ "; jsonQuery += "{ $or : [ "; jsonQuery += "{ sf : { $elemMatch: {'" + SearchField.ValueProperty + "':/^"; jsonQuery += string.Format("{0}/i, ", filterData[0].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'FN'}}}, "; jsonQuery += "{ sf : { $elemMatch: {'" + SearchField.ValueProperty + "':/^"; jsonQuery += string.Format("{0}/i, ", filterData[0].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'PN'}}} "; jsonQuery += "]}, "; jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^"; jsonQuery += string.Format("{0}/i, ", filterData[1].Trim()); jsonQuery += "'" + SearchField.FieldNameProperty + "':'LN'}}}]}]}}"; } } string redisClientIPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("RedisClientIPAddress"); List <PatientData> cohortPatientList = new List <PatientData>(); ServiceStack.Redis.RedisClient client = null; //TODO: Uncomment the following 2 lines to turn Redis cache on //if(string.IsNullOrEmpty(redisClientIPAddress) == false) // client = new ServiceStack.Redis.RedisClient(redisClientIPAddress); //If the redisKey is already in Cache (REDIS) get it from there, else re-query if (client != null && client.ContainsKey(redisKey)) { //go get cohortPatientList from Redis using the redisKey now cohortPatientList = client.Get <List <PatientData> >(redisKey); } else { using (PatientMongoContext ctx = new PatientMongoContext(_dbName)) { BsonDocument searchQuery = BsonSerializer.Deserialize <BsonDocument>(jsonQuery); QueryDocument queryDoc = new QueryDocument(searchQuery); SortByBuilder builder = PatientsUtils.BuildSortByBuilder(querySort); List <MECohortPatientView> meCohortPatients = ctx.CohortPatientViews.Collection.Find(queryDoc) .SetSortOrder(builder).SetSkip(skip).SetLimit(take).Distinct().ToList(); if (meCohortPatients != null && meCohortPatients.Count > 0) { meCohortPatients.ForEach(delegate(MECohortPatientView pat) { if (!pat.DeleteFlag) { PatientData cohortPatient = new PatientData(); cohortPatient.Id = pat.PatientID.ToString(); foreach (SearchField sf in pat.SearchFields) { cohortPatient.FirstName = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.FN).FirstOrDefault()).Value; cohortPatient.LastName = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.LN).FirstOrDefault()).Value; cohortPatient.Gender = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.G).FirstOrDefault()).Value; cohortPatient.DOB = CommonFormatter.FormatDateOfBirth(((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.DOB).FirstOrDefault()).Value); cohortPatient.MiddleName = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.MN).FirstOrDefault()).Value; cohortPatient.Suffix = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.SFX).FirstOrDefault()).Value; cohortPatient.PreferredName = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.PN).FirstOrDefault()).Value; } cohortPatientList.Add(cohortPatient); } }); } } //put cohortPatientList into cache using redisKey now if (client != null) { client.Set <List <PatientData> >(redisKey, cohortPatientList); } } return(cohortPatientList); } catch (Exception) { throw; } }
public Task <IEnumerable <T> > GetPaging(IMongoQuery spec, int idx, int pcount, out long total, SortByBuilder sortBy = null) { throw new NotImplementedException(); }
public QueryData() { Sorts = new SortByBuilder(); }