当前位置: 移动技术网 > IT编程>开发语言>c# > Mongodb在CSharp里实现Aggregate实例

Mongodb在CSharp里实现Aggregate实例

2019年07月18日  | 移动技术网IT编程  | 我要评论
今天主要用了一个mongodb.driver里的分组,事实上在网上介绍这方面的文章非常少,以至于我在出现问题后,无法找到一个正确的解决方案,最后还是通过异常信息找到的解决方

今天主要用了一个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的对象供聚合使用!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网