예제 #1
0
        public List <int> GetYears()
        {
            var result = default(List <int>);
            var aggr   = athletes.Aggregate(new AggregateArgs
            {
                Pipeline = new []
                {
                    AthleteBsonUtil.Groups.Year,
                    AthleteBsonUtil.Aggregates.Sort(AthleteBsonUtil.Fields.Id, Sort.Ascending)
                }
            });

            result = aggr.Select(a => (int)a.First().Value).ToList();
            return(result);
        }
        public List <int> GetYears()
        {
            var result = default(List <int>);
            var aggr   = athletes.Aggregate(new AggregateArgs
            {
                Pipeline = new []
                {
                    YearGroup,
                    YearSort
                }
            });


            result = aggr.Select(a => (int)a.First().Value).ToList();
            return(result);
        }
        public IEnumerable<BsonDocument> Run(MongoCollection<Rental> rentals)
        {
            var priceRange = new BsonDocument(
                "$subtract",
                new BsonArray
                {
                    "$Price",
                    new BsonDocument(
                        "$mod",
                        new BsonArray{"$Price",500}
                        )
                });
            var grouping =new BsonDocument(
                "$group",
                new BsonDocument
                {
                    {"_id",priceRange},
                    {"count",new BsonDocument("$sum",1)}
                });
            var sort=new BsonDocument(
                "$sort",
                new BsonDocument("_id",1)
                );

            var args=new AggregateArgs
            {
                Pipeline=new []{grouping,sort}
            };

            return rentals.Aggregate(args);
        }
        public IEnumerable <BsonDocument> Run(MongoCollection <Rental> rentals)
        {
            var priceRange = new BsonDocument(
                "$subtract",
                new BsonArray
            {
                "$Price",
                new BsonDocument(
                    "$mod",
                    new BsonArray {
                    "$Price", 500
                })
            });
            var grouping = new BsonDocument(
                "$group",
                new BsonDocument
            {
                { "_id", priceRange },
                { "count", new BsonDocument("$sum", 1) }
            });
            var sort = new BsonDocument(
                "$sort",
                new BsonDocument("_id", 1)
                );
            var args = new AggregateArgs
            {
                Pipeline = new[] { grouping, sort }
            };

            return(rentals.Aggregate(args));
        }
예제 #5
0
        public static void Main(string[] args)
        {
            MongoClient   mc  = new MongoClient("mongodb://localhost:27017");
            MongoDatabase mDB = mc.GetServer().GetDatabase("test");

            Console.WriteLine("Got MongoDB Database");

            MongoCollection mColl   = mDB.GetCollection("aggTest");
            AggregateArgs   aggArgs = new AggregateArgs();

            aggArgs.OutputMode = AggregateOutputMode.Cursor;
            aggArgs.Pipeline   = new [] {
                new BsonDocument {
                    {
                        "$match", new BsonDocument {
                            { "a", new BsonInt32(1) }
                        }
                    }
                }
            };


            Console.WriteLine("Complete AggArgs ");
            long        rowCount   = 0;
            IEnumerable aggResults = mColl.Aggregate(aggArgs);

            foreach (BsonDocument doc in aggResults)
            {
                Console.WriteLine("Fetching Agg Result Records in Cursor [" + rowCount + "]");
                ++rowCount;
            }
            Console.WriteLine("Completed Agg result Scan: " + rowCount);
        }
예제 #6
0
        //Se agruparan las alarmas y contaran los campos CH1, CH2 & CH3.
        public List <List <BsonDocument> > MatchFilterPipeline(int value, List <CompanyModel> companyListFixed, MongoCollection rawListCH)
        {
            var ListSL = new List <List <BsonDocument> >();

            for (var i = 0; i < companyListFixed.Count; i++)
            {
                //alarmsListFixed.Add(alarmList[i][j]);
                //Se agrupan los datos segun el formato dado previamente.
                var match = new BsonDocument {
                    {
                        "$match",
                        new BsonDocument {
                            { "planta", companyListFixed[i].Id }
                        }
                    }
                };

                PipelineSetter(match, value);
                var result = rawListCH.Aggregate(new AggregateArgs {
                    AllowDiskUse = true, Pipeline = pipeline
                });

                ListSL.Add(result.ToList());
            }

            return(ListSL);
        }
예제 #7
0
 public IEnumerable <BsonDocument> GetToList()
 {
     return(MongoCollection.Aggregate()
            .Group <BsonDocument>(new BsonDocument()
     {
         { "_id", "$To" },
         { "count", new BsonDocument("$sum", 1) }
     }).ToEnumerable());
 }
        private void GetMetricValue()
        {
            if (DateTime.Now.Subtract(lastPoll).TotalSeconds > _pollingIntervalInSeconds)
            {
                _lastDelay = 0;
                var lastCommitDoc = _commitsCollection.FindAll()
                                    .SetSortOrder(SortBy.Descending("_id"))
                                    .SetFields(Fields.Include("_id"))
                                    .FirstOrDefault();
                if (lastCommitDoc == null)
                {
                    return;
                }

                var lastCommit = lastCommitDoc["_id"].AsInt64;

                //db.checkpoints.aggregate(
                //[
                //    {$match : {"Active": true}}
                //    ,{$project : {"Slot" : 1, "Current" : 1}}
                //    ,{$group : {"_id" : "$Slot", "Current" : {$min : "$Current"}}}
                //])
                BsonDocument[] pipeline =
                {
                    BsonDocument.Parse(@"{$match : {""Active"": true}}"),
                    BsonDocument.Parse(@"{$project : {""Slot"" : 1, ""Current"" : 1}}"),
                    BsonDocument.Parse(@"{$group : {""_id"" : ""$Slot"", ""Current"" : {$min : ""$Current""}}}")
                };
                AggregateArgs args = new AggregateArgs();
                args.Pipeline     = pipeline;
                args.AllowDiskUse = true; //important for large file systems

                var allCheckpoints = _checkpointCollection.Aggregate(args);
                foreach (BsonDocument metric in allCheckpoints)
                {
                    var   slotName = metric["_id"].AsString;
                    Int64 current;
                    if (!metric["Current"].IsBsonNull)
                    {
                        current = Int64.Parse(metric["Current"].AsString);
                    }
                    else
                    {
                        current = 0;
                    }

                    var delay = lastCommit - current;
                    if (delay > _lastDelay)
                    {
                        _lastDelay = delay;
                    }
                    _lastMetrics[slotName] = new SlotStatus(slotName, delay);
                }
                lastPoll = DateTime.Now;
            }
        }
예제 #9
0
 public IEnumerable <BsonDocument> GetControllersByFrom(string to)
 {
     return(MongoCollection.Aggregate()
            .Match(FilterBuilder.Eq("To", to))
            .Group <BsonDocument>(new BsonDocument()
     {
         { "_id", "$Controller" },
         { "count", new BsonDocument("$sum", 1) }
     }).ToEnumerable());
 }
예제 #10
0
        static List <T> Aggregate <T>(IEnumerable <BsonDocument> pipeline)
        {
            var result = _coll.Aggregate(pipeline);

            List <T> returnValues = new List <T>();

            returnValues.AddRange(result.ResultDocuments.Select(x => BsonSerializer.Deserialize <T>(x)));

            return(returnValues);
        }
예제 #11
0
 public IEnumerable <BsonDocument> GetActionsByController(string to, string controller)
 {
     return(MongoCollection.Aggregate()
            .Match(FilterBuilder.Eq("To", to) & FilterBuilder.Eq("Controller", controller))
            .Group <BsonDocument>(new BsonDocument()
     {
         { "_id", "$Action" },
         { "count", new BsonDocument("$sum", 1) }
     }).ToEnumerable());
 }
예제 #12
0
        private IEnumerable <BsonDocument> Aggregate(string collectionName, string aggregationPipeline)
        {
            MongoCollection <BsonDocument> collection = Database.GetCollection <BsonDocument>(collectionName);

            var aggregateArgs = new AggregateArgs();

            if (!string.IsNullOrEmpty(aggregationPipeline))
            {
                aggregateArgs.Pipeline = ParseAggregationPipeline(aggregationPipeline);
            }

            return(collection.Aggregate(aggregateArgs));
        }
예제 #13
0
        public int Sum()
        {
            var group = new BsonDocument
            {
                { "$group",
                  new BsonDocument
                  {
                      { "_id", "" },
                      {
                          "Count", new BsonDocument
                          {
                              { "$sum", "$Count" }
                          }
                      }
                  } }
            };


            var match = new BsonDocument
            {
                {
                    "$match",
                    new BsonDocument
                    {
                        { "Name", new BsonDocument
                          {
                              {
                                  "$in", new BsonArray {
                                      "Determine", "TryMatch"
                                  }
                              }
                          } },
                    }
                }
            };


            var pipeline  = new[] { match, group };
            var result    = collection2.Aggregate(pipeline);
            var Documents = result.ResultDocuments;

            foreach (BsonDocument doc in Documents)
            {
                int t = (int)doc["Count"];

                return(t);
            }


            return(10000);
        }
예제 #14
0
        /// <summary>
        /// 使用管道方法得到类似select B,Max(C),Count(D) from A where x=1 group by B having Count(D)>0的记录
        /// </summary>
        /// <param name="collectionName">表名</param>
        /// <param name="matchDoc">过滤条件</param>
        /// <param name="groupDoc">分组条件</param>
        /// <param name="havingDoc">后面的过滤条件</param>
        /// <returns>记录</returns>
        public IEnumerable <BsonDocument> Aggregate(string collectionName, BsonDocument matchDoc, BsonDocument groupDoc,
                                                    BsonDocument havingDoc)
        {
            MongoCollection collection = GetMongoCollection(collectionName);
            AggregateResult result     = collection.Aggregate(matchDoc, groupDoc, havingDoc);

            if (result.Ok)
            {
                return(result.ResultDocuments);
            }
            else
            {
                return(null);
            }
        }
예제 #15
0
        private StatisticItem GetStatisticItem(DateTime startStroke, DateTime endStroke, MongoCollection <Session> sessions)
        {
            var match       = GetMatchOperator(startStroke, endStroke);
            var project     = GetProjectOperator(startStroke);
            var project1    = GetProjectOperator1();
            var group       = GetGroupOperator();
            var pipeline    = new[] { match, project, group, project1 };
            var queryResult = sessions.Aggregate(pipeline);
            var items       = queryResult.ResultDocuments.ToList();

            var doc    = queryResult.ResultDocuments.Select(BsonSerializer.Deserialize <StatisticItem>).FirstOrDefault();
            var count  = doc == null ? 0 : doc.Count;
            var result = new StatisticItem {
                DateTime = startStroke, Count = count
            };

            return(result);
        }
예제 #16
0
 public IEnumerable <BsonDocument> OpRecordDay(DateTime createTime)
 {
     return(MongoCollection.Aggregate()
            .Match(FilterBuilder.Gte("CreateTime", createTime))
            .Project(new BsonDocument("date", new BsonDocument("$dateToString", new BsonDocument()
     {
         { "format", "%Y-%m-%d" },
         { "timezone", AppSettings.GetValue("timezone") },
         { "date", "$CreateTime" }
     }
                                                               )))
            .Group <BsonDocument>(new BsonDocument()
     {
         { "_id", "$date" },
         { "count", new BsonDocument("$sum", 1) }
     })
            .Sort(new BsonDocument("_id", 1)).ToEnumerable());
 }
예제 #17
0
        private StatisticItem GetStatisticItem(DateTime startStroke, DateTime endStroke, MongoCollection<Session> sessions)
        {
            var match = GetMatchOperator(startStroke, endStroke);
            var project = GetProjectOperator(startStroke);
            var project1 = GetProjectOperator1();
            var group = GetGroupOperator();
            var pipeline = new[] { match, project, group, project1 };
            var queryResult = sessions.Aggregate(pipeline);
            var items = queryResult.ResultDocuments.ToList();

            var doc = queryResult.ResultDocuments.Select(BsonSerializer.Deserialize<StatisticItem>).FirstOrDefault();
            var count = doc == null ? 0 : doc.Count;
            var result = new StatisticItem { DateTime = startStroke, Count = count };
            return result;
        }
예제 #18
0
 public IEnumerable <BsonDocument> Aggregate(AggregateArgs aggregateArgs)
 {
     return(_collection.Aggregate(aggregateArgs));
 }
예제 #19
0
        public IEnumerable <MongoRange> GetNewest(Dictionary <string, object> matchData)
        {
            /*
             *
             * db.tmqStats.aggregate({$match:{ch:"4", z:"5"}}, { $sort: { Left: 1 } },
             * {$group:{_id:"$SecondsInterval", Left:{$last:"$Left"}, id:{$last:"$_id"}, Counter:{$last:"$Counter"}}},
             * {$project:{_id:"$id",SecondsInterval:"$_id", Left:1, Counter:1}})
             *
             */

            var match = new BsonDocument
            {
                {
                    "$match",
                    new BsonDocument(matchData)
                }
            };
            var sort = new BsonDocument
            {
                {
                    "$sort",
                    new BsonDocument("Left", 1)
                }
            };
            var group = new BsonDocument
            {
                {
                    "$group",
                    new BsonDocument
                    {
                        {
                            "_id", "$SecondsInterval"
                        },
                        {
                            "Left", new BsonDocument
                            {
                                { "$last", "$Left" }
                            }
                        },
                        {
                            "id", new BsonDocument
                            {
                                { "$last", "$_id" }
                            }
                        },
                        {
                            "Counter", new BsonDocument
                            {
                                { "$last", "$Counter" }
                            }
                        }
                    }
                }
            };

            var project = new BsonDocument
            {
                {
                    "$project",
                    new BsonDocument
                    {
                        //{"_id","$id"},
                        { "_id", 0 },
                        { "SecondsInterval", "$_id" }, { "Left", 1 }, { "Counter", 1 }
                    }
                }
            };
            var pipeline = new[] { match, sort, group, project };

            CheckConnection();
            var result = Collection.Aggregate(pipeline);

            foreach (var item in result.ResultDocuments)
            {
                //item.Add(matchData);
                yield return(MongoDB.Bson.Serialization.BsonSerializer.Deserialize <MongoRange>(item));
            }
        }
예제 #20
0
        /// <summary>
        /// Calculate the amount of documents
        /// </summary>
        /// <param name="name">Field name to group by</param>
        /// <returns>Document list represented by "Key" and "Value" inside aggregate result object</returns>
        public AggregateResult GroupByCount(string name, MongoCollection collection, BsonDocument sort, BsonDocument limit, BsonDocument skip, BsonDocument match, bool countGroups =false)
        {
            // prepare pipeline operations
            var group = new BsonDocument
            {
                {
                    "$group",
                    new BsonDocument
                    {
                        {
                            "_id", new BsonDocument
                            {
                                {
                                    "Key","$" + name
                                }
                            }
                        },
                        {
                            "Value", new BsonDocument
                            {
                                {
                                    "$sum", 1
                                }
                            }
                        }
                    }
                }
            };

            var project = new BsonDocument
            {
                {
                    "$project",
                    new BsonDocument
                    {
                        {"_id", 0}, // remove reference to _id
                        {"Key","$_id.Key"}, // set reference to "_id.Name" as "UserName"
                        {"Value", 1}, // dont  change "Count"
                    }
                }
            };

            List<BsonDocument> pipeline = new List<BsonDocument>{ };
            if (match != null)
                pipeline.Add(match);

            pipeline.Add(group);
            if (countGroups)
            {
                var total = new BsonDocument
                {
                    {
                        "$group",
                        new BsonDocument
                        {
                            {
                                "_id", 0
                            },
                            {
                                "Total", new BsonDocument
                                {
                                    {
                                        "$sum", 1
                                    }
                                }
                            }
                        }
                    }
                };

                pipeline.Add(total);
            }
            else
            {
                pipeline.Add(project);

                if (sort != null)
                {
                    pipeline.Add(sort);
                }
                pipeline.Add(skip);
                pipeline.Add(limit);
            }
            collection.EnsureIndex(IndexKeys.Ascending(name));
            return collection.Aggregate(pipeline);
        }
예제 #21
0
        public List <MetricGroup> WeeklyActions()
        {
            var group = new BsonDocument
            {
                { "$group",
                  new BsonDocument
                  {
                      { "_id",
                                                new BsonDocument
                                                {
                                                    { "Name", "$Name" }
                                                } },
                      {
                          "Count", new BsonDocument
                          {
                              { "$sum", 1 }
                          }
                      }
                  } }
            };
            var project = new BsonDocument
            {
                {
                    "$project",
                    new BsonDocument
                    {
                        { "_id", 0 },
                        { "Name", "$_id.Name" },
                        { "Count", 1 },
                    }
                }
            };
            var sort = new BsonDocument
            {
                { "$sort",
                  new BsonDocument
                  {
                      { "Count", 1 },
                  } }
            };
            var match = new BsonDocument
            {
                {
                    "$match",
                    new BsonDocument   {
                        {
                            "Date", new BsonDocument
                            {
                                {
                                    "$gt", Convert.ToInt32(DateTime.Now.AddDays(-7).ToString("yyyyMMdd"))
                                }
                            }
                        }
                    }
                }
            };

            var pipeline         = new[] { match, group, project, sort };
            var result           = collection.Aggregate(pipeline);
            var Documents        = result.ResultDocuments;
            List <MetricGroup> L = new List <MetricGroup>();

            foreach (BsonDocument doc in Documents)
            {
                MetricGroup M = new MetricGroup();
                M.Y = (int)doc["Count"];
                M.X = doc["Name"] == BsonNull.Value ? "" : (string)doc["Name"];
                L.Add(M);
            }
            return(L);
        }