gpt4 book ai didi

mongodb - Map-Reduce count 每分钟 MongoDB 的文档数

转载 作者:IT老高 更新时间:2023-10-28 13:35:00 24 4
gpt4 key购买 nike

我有一个 MongoDB 集合,它在每个文档中存储了一个 created_at。这些存储为 MongoDB 日期对象,例如

{ "_id" : "4cacda7eed607e095201df00", "created_at" : "Wed Oct 06 2010 21:22:23 GMT+0100 (BST)", text: "something" }
{ "_id" : "4cacdf31ed607e0952031b70", "created_at" : "Wed Oct 06 2010 21:23:42 GMT+0100 (BST)", text: "something" }
....

我想计算每分钟之间创建的项目数,因此我可以将数据传递到 Google Charts 以生成如下内容:

alt text

我如何使用 map reduce 函数来做到这一点,或者有没有我可以使用的花哨的 MongoDB 聚合函数?

最佳答案

Map 函数应该发出一个时间戳对象,调整到分钟,计数为 1。reduce 函数应该对所有计数求和:

map = function() {
var created_at_minute = new Date(this.created_at.getFullYear(),
this.created_at.getMonth(),
this.created_at.getDate(),
this.created_at.getHours(),
this.created_at.getMinutes());
emit(created_at_minute, {count: 1});
}

reduce = function(key, values) {
var total = 0;
for(var i = 0; i < values.length; i++) {
total += values[i].count;
}
return {count: total};
}

关于mongodb - Map-Reduce count 每分钟 MongoDB 的文档数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3879371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com