如何从 MongoDB 中抽取 N 个样本数据来形成整个数据集的图形表示?

How to take data N samples from MongoDB to form a graph representation on whole data set?

这是我们新应用程序中的示例文档,用于将时间序列数据存储在 MongoDB 子文档中,

{
    "_id" : ObjectId("5dcb6cacfb315e66b551a1a0"),
    "youtubeId" : "bIWShN9rKQU",
    "views" : [ 
        {
            "count" : 17506,
            "at" : ISODate("2019-08-12T13:31:00.002Z")
        }, 
        {
            "count" : 29576,
            "at" : ISODate("2019-11-14T13:32:00.216Z")
        }, 
        {
            "count" : 29579,
            "at" : ISODate("2019-11-15T13:33:00.197Z")
        }, 
        {
            "count" : 29582,
            "at" : ISODate("2019-11-16T13:34:00.192Z")
        }, 
        {
            "count" : 29586,
            "at" : ISODate("2019-11-17T13:35:00.180Z")
        }, 
        {
            "count" : 29595,
            "at" : ISODate("2019-11-19T13:36:00.190Z")
        }, 
        {
            "count" : 29597,
            "at" : ISODate("2019-11-20T13:37:00.206Z")
        }, 
        {
            "count" : 29604,
            "at" : ISODate("2019-11-21T13:38:00.228Z")
        }, 
        {
            "count" : 29606,
            "at" : ISODate("2019-11-22T13:39:00.218Z")
        }, 
        {
            "count" : 29613,
            "at" : ISODate("2019-11-24T13:40:00.201Z")
        }, 
        {
            "count" : 29619,
            "at" : ISODate("2019-11-25T13:41:00.250Z")
        }, 
        {
            "count" : 29624,
            "at" : ISODate("2019-11-27T13:42:00.103Z")
        }, 
        {
            "count" : 29636,
            "at" : ISODate("2019-11-29T13:43:00.128Z")
        }
    ]
}

现在,我想在移动应用程序使用的 Web 服务中发送此数据以绘制图形,但我只想在 views 数组中获取 10 个对象,这应该表示 关于时间的整个数据集。但是无论数组大小,都应该是10个数据。

如何使用 at 时间戳字段从整个数据集中提取 10 个数据来创建整个数据的表示?

In the above example views is an object array, which has times from 2019-08-12T13:31:00.002Z to 2019-11-29T13:43:00.128Z (13 records as 1/ minute), so that 5 samples from that means one record per every 2 minutes approximately

var noOfSamples = 5

db.test.aggregate( [
{ 
  $addFields: { 
      indexes: { 
          $range: [ 0, 
                    { $size: "$views" }, 
                    { $ceil: { $divide: [ { $size: "$views" }, noOfSamples ] } } 
                  ]
      } 
  }
},
{ 
  $project: { 
      sample: { 
          $map: {
              input: "$indexes",
                 as: "ix",
                 in: { $arrayElemAt: [ "$views", "$$ix" ] }
          }
      }
   }
}
] )



备注:

你想要的样本数是5,noOfSamplesviews 数组的大小为 13.

views中的元素个数除以noOfSamples;在本例中,您得到的值为 2.6$ceil 将其舍入为下一个舍入整数,即 3(我们称之为 "step")。 $range 运算符为您提供一个 0 到 12 之间的数字数组,步长为 3(0 是 views 数组的第一个索引,12 是数组的最高索引)。在聚合的第一阶段,您会得到一个名为 indexes: [ 0, 3, 6, 9, 12 ] 的数组。

在聚合的第二阶段,使用前一阶段生成的indexes,通过索引获得views个数组元素。 $map 聚合数组运算符 映射 indexesviews 数组元素的生成索引 - 所以你从 [=12= 得到五个元素] 数组作为示例。