草庐IT

mongodb - 运行查询时mongo上的聚合函数运行速度非常慢

coder 2023-11-07 原文

尝试在 Mongo 上的聚合函数上运行查询,目前需要 16 秒,而我希望的结果不到一秒

{
  "$lookup": {
    "from": "session_attendances",
    "let": { "id": "$_id" },
    "pipeline": [
      {
        "$match": {
          "$expr": {
            "$eq": ["$student", "$$id"]
          }
        }
      },
      {
        "$project": {
          "attendance_code": "$attendance_code"
        }
      }
    ],
    "as": "attendance"
  }
},
{
  // keep only matched students, can skip this and modifiy the next phase incase no such documents exists.
  "$unwind": "$attendance"
},
{
  "$lookup": {
    "from": "attendance_codes",
    "let": { "attendance_code": "$attendance.attendance_code" },
    "pipeline": [
      {
        "$project": {
          "type": 1
        }
      },
      {
        "$match": {
          "$expr": {
            "$eq": ["$_id", "$$attendance_code"]
          }
        }
      }
    ],
    "as": "attendance_code"
  }
},
{
  //again assuming we want to keep matched docs otherwise why lookup?
  "$unwind": "$attendance_code"
},
{
  "$group": {
    "_id": { "a": "$attendance.attendance_code", "id": "$_id" },
    "total": { "$sum": 1 },
    "data": { "$first": "$$ROOT" } // if u want to keep document data
  }
}

希望有人能回答我是我的代码的哪一部分导致运行时间如此缓慢。

最佳答案

不清楚你的最终目标是什么,如果你想澄清它会帮助我为你当前的聚合提供一个替代方案

也就是说,第二个查找阶段是“无用的”,因为您在不使用它获得的任何数据的情况下立即进行分组,删除它仍然会得到完全相同的结果并节省一些时间。

假设出于某种原因需要第二次查找,我建议不要嵌套它,而是在第一次查找之后使用,如下所示:

{
        $lookup: {
            from: 'session_attendances',
            let: { 'id': '$_id' },
            pipeline: [
                {
                    "$match": {
                        "$expr": {
                            "$eq": ["$student", "$$id"]
                        }
                    }
                }
                ,{
                    $project: {
                        attendance_code: '$attendance_code'
                    }
                }
            ],
            as: 'attendance'
        }
    },
    {// keep only matched students, can skip this and modifiy the next phase incase no such documents exists.
       $unwind: "$attendance" 
    },
    {
       $lookup: {
           from: 'attendance_codes',
           let: { 'attendance_code': '$attendance.attendance_code' },
            pipeline: [
               {
                 $project: {
                    type: 1
                 }
               },
               {
                 "$match": {
                     "$expr": {
                         "$eq": ["$_id", "$$attendance_code"]
                   }
               }],
               as: 'attendance_code'
                    }
         }
   },
   { //again assuming we want to keep matched docs otherwise why lookup?
     $unwind: "$attendance_code"
   },
   {
        $group: {
            _id: {a: "$attendance.attendance_code", id: "$_id"}
            total: { $sum: 1 },
            data: {$first: "$$ROOT"} // if u want to keep document data
       } 
   }

这应该会给你更好的性能,我还建议放弃项目阶段,除非文档非常大,否则这通常不会提高性能,反而会损害性能。

关于mongodb - 运行查询时mongo上的聚合函数运行速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415532/

有关mongodb - 运行查询时mongo上的聚合函数运行速度非常慢的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  3. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  6. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  7. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  8. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  9. ruby-on-rails - openshift 上的 rails 控制台 - 2

    我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新ruby​​gems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems

  10. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

随机推荐