文章出處

回到目錄 

今天主要用了一個mongodb.driver里的分組,事實上在網上介紹這方面的文章非常少,以至于我在出現問題后,無法找到一個正確的解決方案,最后還是通過異常信息找到的解決方法,所以感覺自己更應該去寫一篇關于如何在C#驅動里進行聚合Aggregate的文章!

        /// <summary>
        /// 返回UI消息樹
        /// </summary>
        /// <returns></returns>
        public static string GetMongoLog(DateTime? fromDate, DateTime? toDate, int page = 1)
        {
            string from = DateTime.Now.Date.ToString("yyyy-MM-dd");
            string to = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd");
            if (fromDate.HasValue)
            {
                from = fromDate.Value.ToString("yyyy-MM-dd");

            }
            if (toDate.HasValue)
            {
                to = toDate.Value.ToString("yyyy-MM-dd");
            }
            var stages = new List<IPipelineStageDefinition>();
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$match:{AddTime:{$gt:ISODate('" + from + "'),$lt:ISODate('" + to + "')}}}"));
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: \"$RootId\", count: {$sum: 1}}}"));
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$skip:" + page * 5 + "}"));
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$limit:5}"));
            var pipeline = new PipelineStagePipelineDefinition<BsonDocument, BsonDocument>(stages);
            var result = NoSql.MongodbManager<LoggerContext>.Collection.Aggregate(pipeline);
            StringBuilder str = new StringBuilder();

            str.Append("<ol class='treeMsg'>");
            foreach (var item in result.ToList())
            {
                var timer = new List<DateTime>();
                var old = NoSql.MongodbManager<LoggerContext>.Instance.Find(i => i.RootId == item.Values.ToArray()[0].ToString() && i.ParentId == null).FirstOrDefault();
                timer.Add(old.AddTime);
                str.Append("<li style='margin:5px;border:1px dashed #aaa'>");
                str.AppendFormat("<span style='color:red;'>{0}</span><span style='color:green'>{1}</span><span>{2}</span>"
                   , old.Url
                   , old.MessageBody
                   , old.AddTime);
                MsgTree(str, old.ChildId, timer);
                str.AppendFormat("<p><b><em>本次請求用時{0}毫秒({1}秒)<em></b></p>"
                    , (timer.Max() - timer.Min()).TotalMilliseconds
                    , (timer.Max() - timer.Min()).TotalSeconds);
                str.Append("</li>");
            }
            str.Append("</ol>");
            return str.ToString();
        }

注意,目前mongodb for C#這個驅動,在進行Aggregate時,只支持BsonDocument類型,也就是說,你的集合collection也必須返回的是BsonDocument,而實體類型是不可以被認出的,這點要注意.

也正是如此,所以我們的mongo封裝時,別忘記公開一個BsonDocument的對象供聚合使用!

感謝各位的閱讀,希望文章可以幫助大家!

 回到目錄


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()