jjzjj

Mongodb聚合查询对累积值进行减法和分组

coder 2023-05-05 原文

{
"_id" : ObjectId("58f5a22d22679039176d2ee8"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:01:01.000+05:30"), 
"Utilization" : NumberInt("63654480"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681350")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2ee9"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:02:02.000+05:30"), 
"Utilization" : NumberInt("63655480"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681370")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2eea"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:03:02.000+05:30"), 
"Utilization" : NumberInt("63656480"),
"RunStatus" : NumberInt("0"),   
"ProductsCount" : NumberInt("681390")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2eeb"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:04:02.000+05:30"), 
"Utilization" : NumberInt("63657480"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681420")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2eec"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:05:02.000+05:30"), 
"Utilization" : NumberInt("63658480"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681450"),  
},
{
"_id" : ObjectId("58f5a22d22679039176d2eed"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:06:02.000+05:30"), 
"Utilization" : NumberInt("63659480"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681470")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2eee"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:07:02.000+05:30"), 
"Utilization" : NumberInt("63659780"),
"RunStatus" : NumberInt("0"),   
"ProductsCount" : NumberInt("681490")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2eef"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:08:03.000+05:30"), 
"Utilization" : NumberInt("63659880"),
"RunStatus" : NumberInt("1"),   
"ProductsCount" : NumberInt("681525")   
},
{
"_id" : ObjectId("58f5a22d22679039176d2ef0"),
"MachineID" : NumberInt("1001"),
"Timestamp" : ISODate("2017-04-18T07:09:03.000+05:30"), 
"Utilization" : NumberInt("63659980"),
"RunStatus" : ("0"),
"ProductsCount" : NumberInt("681563")
}

从上述集合中,UtilizationProductsCount 是累积值,并且随时间递增。

需要减去当前行的Utilization和下一行的Utilization,按升序排列。以及基于 RunStatusProductsCount 的相同操作。

如果当前行的RunStatus为1,下一行为0,则UtilizationProductsCount的差异应该映射到RunStatus 为 0。

然后根据MachineIDRunStatus

进行分组

预期结果

/* 1 */
{   
"MachineID" : 1001,
"RunStatus" : 1,
"Utilization" : 4100,
"ProducedCount" : 135
},

/* 2 */
{   
"MachineID" : NumberInt("1001"),
"RunStatus" : NumberInt("0"),
"Utilization" : 1400,
"ProducedCount" : 78
}

聚合框架需要结果。请帮忙。

这是我试过的,

db.collection.aggregate([
{ "$match" : { "$and" : [ { "MachineID" : { "$in" : [ 1001]}} , 
    { "Timestamp" : { "$gte" : ISODate("2017-04-18T01:30:00.000Z"), 
    "$lte" : ISODate("2017-04-19T01:30:00.000Z")}},]}
}, 
{
    "$addFields": {"lastUtilization": 0}
},
{
    "$addFields": {"lastProductsCount" : 0}
},
{
    "$group": {
        "_id": 
        {
             MachineID : '$MachineID',
            "RunStatus": "$RunStatus"
        },
        "Utilization" : 
        {
            "$sum" : 
            {
                "$cond": [
                        { "$ne": [ "$lastUtilization", 0 ] },
                         {"$subtract" : ["$Utilization", 
"$lastUtilization"]}, 0
                    ]
            }
        }, 
        "ProductsCount" : 
        {
            "$sum" : 
            {
                "$cond": [
                        { "$ne": [ "$lastProductsCount", 0 ] },
                         {"$subtract" : ["$ProductsCount", 
"$lastProductsCount"]}, 0
                    ]
            }
        }, 
        "lastProductsCount" : { "$avg" : "$ProductsCount"}, 
        "lastUtilization" : { "$avg" : "$Utilization"}
}
},
{
    "$project": 
    {
        "MachineID": "$_id.MachineID", 
        "RunStatus" : "$_id.RunStatus", 
        "Utilization" : "$Utilization", 
        "ProductsCount" : "$ProductsCount"
    }
},
]);

最佳答案

这是怎么回事?它不计算小时,但它会做其他所有事情。

[
    {
      $match: {
          $and: [
              {MachineID: {$in: [1001]}},
              {
                Timestamp: {
                    $gte: ISODate("2017-04-18T01:30:00.000Z"),
                    $lte: ISODate("2017-04-19T01:30:00.000Z")
                }
              }
          ]
      }
    },
    // Add all data to one array.
    {$group: {_id: "$MachineID", all: {$push: "$$ROOT"}}},
    // Create an array of (element, array index) pairs.
    {$addFields: {allWithIndex: {$zip: {inputs: ["$all", {$range: [0, {$size: "$all"}]}]}}}},
    // Create an array of {current: <element>, previous: <previous element>} pairs.
    {
      $project: {
          pairs: {
              $map: {
                  input: "$allWithIndex",
                  in : {
                      current: {$arrayElemAt: ["$$this", 0]},
                      prev: {
                          $arrayElemAt: [
                              "$all",
                              // Set prev == current for the first element.
                              {$max: [0, {$subtract: [{$arrayElemAt: ["$$this", 1]}, 1]}]}
                          ]
                      }
                  }
              }
          }
      }
    },
    // Compute the deltas.
    {$unwind: "$pairs"},
    {
      $group: {
          _id: {MachineID: "$_id", RunStatus: "$pairs.current.RunStatus"},
          ProductsCount:
              {$sum: {$subtract: ["$pairs.current.ProductsCount", "$pairs.prev.ProductsCount"]}},
          Utilization:
              {$sum: {$subtract: ["$pairs.current.Utilization", "$pairs.prev.Utilization"]}},
      }
    }
]

关于Mongodb聚合查询对累积值进行减法和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560777/

有关Mongodb聚合查询对累积值进行减法和分组的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. 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.

  4. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  5. ruby - 如何进行排列以有效地定制输出 - 2

    这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][

  6. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  7. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  8. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  9. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  10. ruby - 在 Ruby 中创建按公共(public)键值分组的新哈希 - 2

    假设我有一个在Ruby中看起来像这样的哈希:{:ie0=>"Hi",:ex0=>"Hey",:eg0=>"Howdy",:ie1=>"Hello",:ex1=>"Greetings",:eg1=>"Goodday"}有什么好的方法可以将它变成如下内容:{"0"=>{"ie"=>"Hi","ex"=>"Hey","eg"=>"Howdy"},"1"=>{"ie"=>"Hello","ex"=>"Greetings","eg"=>"Goodday"}} 最佳答案 您要求一个好的方法来做到这一点,所以答案是:一种您或同事可以在六个月后理解

随机推荐