为MongoDB查询duong,但允许某些基于时间戳的重复项

所以我有一组数据与时间戳相关联。 我想让mongo在3分钟的时间戳内重复那些重复的。 我会告诉你一个我的意思的例子:

原始数据:

[{"fruit" : "apple", "timestamp": "2014-07-17T06:45:18Z"}, {"fruit" : "apple", "timestamp": "2014-07-17T06:47:18Z"}, {"fruit" : "apple", "timestamp": "2014-07-17T06:55:18Z"}] 

查询后,会是:

 [{"fruit" : "apple", "timestamp": "2014-07-17T06:45:18Z"}, {"fruit" : "apple", "timestamp": "2014-07-17T06:55:18Z"}] 

因为第二个条目是在第一个条目创build的3分钟内。 我已经得到了代码,以便聚合和删除具有相同水果的模糊,但现在我只想结合在时间戳泡沫内的模糊。

我们应该可以做到这一点! 首先让我们用3分钟的时间泡一小时

[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57]

现在将这些文档分组,我们需要稍微修改时间戳。 据我所知,这是目前不可能的聚合框架,所以相反,我会使用group()方法。

为了在相同的时间内分组水果,我们需要将时间戳设置为最接近分钟的“泡沫”。 我们可以用timestamp.minutes -= (timestamp.minutes % 3)来做到这一点。

这是查询结果:

 db.collection.group({ keyf: function (doc) { var timestamp = new ISODate(doc.timestamp); // seconds must be equal across a 'bubble' timestamp.setUTCSeconds(0); // round down to the nearest 3 minute 'bubble' var remainder = timestamp.getUTCMinutes() % 3; var bubbleMinute = timestamp.getUTCMinutes() - remainder; timestamp.setUTCMinutes(bubbleMinute); return { fruit: doc.fruit, 'timestamp': timestamp }; }, reduce: function (curr, result) { result.sum += 1; }, initial: { sum : 0 } }); 

示例结果:

 [ { "fruit" : "apple", "timestamp" : ISODate("2014-07-17T06:45:00Z"), "sum" : 2 }, { "fruit" : "apple", "timestamp" : ISODate("2014-07-17T06:54:00Z"), "sum" : 1 }, { "fruit" : "banana", "timestamp" : ISODate("2014-07-17T09:03:00Z"), "sum" : 1 }, { "fruit" : "orange", "timestamp" : ISODate("2014-07-17T14:24:00Z"), "sum" : 2 } ] 

为了使这更容易,您可以预先计算“泡泡”时间戳并将其作为单独的字段插入到文档中。 你创build的文件看起来像这样:

 [ {"fruit" : "apple", "timestamp": "2014-07-17T06:45:18Z", "bubble": "2014-07-17T06:45:00Z"}, {"fruit" : "apple", "timestamp": "2014-07-17T06:47:18Z", "bubble": "2014-07-17T06:45:00Z"}, {"fruit" : "apple", "timestamp": "2014-07-17T06:55:18Z", "bubble": "2014-07-17T06:54:00Z"} ] 

当然,这占用更多的存储空间。 但是,使用这个文档结构,您可以使用聚合函数[0]。

 db.collection.aggregate( [ { $group: { _id: { fruit: "$fruit", bubble: "$bubble"} , sum: { $sum: 1 } } }, ] ) 

希望有所帮助!

MongoDB聚合比较:group(),$ group和MapReduce