private static FieldsBuilder ParseProjection(string projection) { var fields = new FieldsBuilder(); if (String.IsNullOrEmpty(projection)) return fields; var projectionDocument = BsonSerializer.Deserialize<BsonDocument>(projection); foreach (var element in projectionDocument) { var value = element.Value; if (value.IsBoolean && value.AsBoolean || value.IsInt32 && value.AsInt32 != 0) { fields.Include(element.Name); } else if (value.IsBoolean && !value.AsBoolean || value.IsInt32 && value.AsInt32 == 0) { fields.Exclude(element.Name); } else { throw Errors.InvalidProjectionFormat(); } } return fields; }
public IEnumerable<AggregatedValue> Find(DateTime startDate, DateTime endDate, Dictionary<string, List<string>> props) { MongoCollection<StoredCounter> items = MongoDb.GetCollection<StoredCounter>("countersData"); IMongoQuery q = Query.And(Query.GTE("date", startDate), Query.LT("date", endDate)); FieldsBuilder fields = new FieldsBuilder(); //fields.Include("date", "data.Max", "data.Min", "data.Count", "data.Avg", "data.Sum"); fields.Include("date", "data"); foreach (KeyValuePair<string, List<string>> prop in props) { string fieldName = "props." + prop.Key; fields.Include(fieldName); if (prop.Value.Count == 0) q = Query.And(q, Query.Exists(fieldName)); else if (prop.Value.Count == 1) q = Query.And(q, Query.EQ(fieldName, prop.Value.First())); else q = Query.And(q, Query.In(fieldName, prop.Value.Cast<BsonString>())); } MongoCursor cursor = items.Find(q); cursor.SetFields(fields); cursor.SetSortOrder(SortBy.Ascending("date")); Stopwatch sw = Stopwatch.StartNew(); var found = cursor.Cast<object>().ToList(); sw.Stop(); Console.WriteLine( found.Count + " entries fetched from db in " + sw.ElapsedMilliseconds + " ms"); sw.Restart(); var parsed = found.Cast<StoredCounter>().Select(ParseAggregatedValue).ToList(); sw.Stop(); Console.WriteLine(parsed.Count + " entries parsed in " + sw.ElapsedMilliseconds + " ms"); sw.Restart(); var result = parsed.Compact().ToList(); sw.Stop(); Console.WriteLine(found.Count + " entries compacted to " + result.Count + " in " + sw.ElapsedMilliseconds + " ms"); return result; }
public static IMongoFields ObjectsToFields(IList<object> values) { if (values == null) return null; IMongoFields fields; if (values.Count == 1 && (fields = values[0] as IMongoFields) != null) return fields; var builder = new FieldsBuilder(); foreach (var it in values) { var name = it as string; if (name != null) { builder.Include(name); continue; } throw new ArgumentException("Property: Expected either one IMongoFields or one or more String."); } return builder; }