简体   繁体   English

从mongodb阵列获取最近2天/分钟

[英]get last 2 days/minutes from mongodb array

I have mongodb data like this: 我有像这样的mongodb数据:

"_id" : "sensor-2",
"data" : [ 
    {
        "sensor" : {
            "intensitas" : 3,
            "arus" : 0.1
        },
        "tanggal" : ISODate("2018-08-05T21:00:19.552+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 8,
            "arus" : 0.1
        },
        "tanggal" : ISODate("2018-08-05T21:04:40.594+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 6,
            "arus" : 0.1
        },
        "tanggal" : ISODate("2018-08-05T21:05:43.647+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 13,
            "arus" : 0.1
        },
        "tanggal" : ISODate("2018-08-04T21:05:45.150+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 15,
            "arus" : 0.05
        },
        "tanggal" : ISODate("2018-08-04T21:05:46.651+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 13,
            "arus" : 0.05
        },
        "tanggal" : ISODate("2018-08-04T21:05:51.152+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 8,
            "arus" : 0.05
        },
        "tanggal" : ISODate("2018-08-04T21:05:52.654+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 11,
            "arus" : 0.05
        },
        "tanggal" : ISODate("2018-08-04T21:05:58.756+07:00")
    }, 
    {
        "sensor" : {
            "intensitas" : 3,
            "arus" : 0.05
        },
        "tanggal" : ISODate("2018-08-07T21:05:58.757+07:00")
    }
]

I want to get the last 2 days or minutes from the array base from id, which "tanggal" is Date in English. 我想从数组中获取ID的最后2天或分钟,而“ tanggal”是英语中的Date。

I've tried from this how to filter last 10 days records from mongoDb? 我已经尝试过如何从mongoDb过滤最近10天的记录? but not what I want because after I get the data I want to average that last 2 days/minutes data. 但不是我想要的,因为获取数据后,我想对过去2天/分钟的数据进行平均。

To get the last 2 days you can do something like this: 要获得最后2天的时间,您可以执行以下操作:

db.getCollection('items').aggregate([
  {
      $unwind: '$data'
  },
  {
    $match: {
      'data.tanggal': {
        $gt: (new Date(new ISODate()-2*1000*60*60*24))
      }
    }
  },
  {
    $sort: {
      'data.tanggal': -1
    }
  }
])

last 2 minutes you just remove the 24 from the date calc so you get: 最后2分钟,您只需从日期计算中删除24 ,即可得到:

$gt: (new Date(new ISODate()-2*1000*60*60))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM