node.js - 查找两个文档的日期差异

标签 node.js mongodb express mongoose

我有一个包含以下文档的集合:

{ type: 1,
  user: 1,
  date: "2019-01-01 11:52"
},
{ type: 1,
  user: 2,
  date: "2019-01-01 11:55"
},
{ type: 2,
  user: 2,
  date: "2019-01-01 12:02"
},
{ type: 2,
  user: 1,
  date: "2019-01-01 12:10"
},

我想找到不同类型和同一用户花费的时间。例如:

{ user: 1,
  time: 18// minutes
},
{ user: 2,
  time: 7
}

Mongoose 怎么能做到这一点?

最佳答案

我假设每个用户只会有两个文档。如果您想计算每个用户两种以上类型之间的时间差,我的答案会有所不同。以下是我为实现这一目标将采取的步骤:

  • 使用 find() 函数从 MongoDB 获取集合。

  • 创建一个新的空对象来保存结果。

  • 循环遍历集合中的每个文档:

  • 如果结果对象中不存在用户 ID,请将用户及其类型和日期添加到结果对象中。

  • 如果结果对象中已存在该用户 ID,则计算该文档与结果对象中先前保存的日期之间的时间差。

  • 从结果集合中删除类型和日期。

代码(未测试)

/* Get the collection from MongoDB. */
collection_name.find({}, function (err, collection) {
    if (err) {
      return console.log(err);
    } else {
        /* Create results object */
        var results = {};
        /* Loop over each document in the collection. */
        for(doc in collection){
            /* If the user doesn't exist in the results object. */
            if(typeof results[doc.user] == 'undefined'){
                /* Add the user to the results object. */
                results[doc.user] = {"type": doc.type, "date": doc.date};
            }
            /* If the user already exists in the results object. */
            else if(typeof results[doc.user] != 'undefined'){
                /* Calculate the time difference in milliseconds. */
                var diff = Math.abs(new Date(results[doc.user].date) - new Date(doc.date));
                /* Convert to minuets and save to results. */
                results[doc.user].time = Math.floor((diff/1000)/60);
                /* Remove date and type from results. */
                delete results[doc.user].date;
                delete results[doc.user].type;
            }
         }
         console.log(results);
     }
});

生成的对象应如下所示:

{
 1: {
  "time": 3 
 },
 2: {
  "time": 5
 },
 3: {
  "time": 2 
 },
 4: {
  "time": 4 
 }
}

结果对象中的键是用户 ID。该程序计算每个用户不同类型的两个文档的两个日期之间的绝对时间差(以分钟为单位)。如果你想计算两种以上类型之间的时间差,代码会稍微复杂一些。

关于node.js - 查找两个文档的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54921150/

相关文章:

node.js - npm: module.js:457 抛出错误;错误:使用 brew 在 mac 上找不到模块 'npmlog'

linux - 为什么不在一个 Amazon EC2 实例上运行 Node.js 和 Neo4j

node.js - Node : Callback was already called

python - 在python中通过身份验证连接到套接字

javascript - app.use 在发送错误后出现 Can\t set headers 错误

node.js - 如何将变量从 Jade 模板文件传递到 Javascript 文件?

javascript - 具有到期时间的 Google Cloud Storage ACL

arrays - MongoDB统计最常见的嵌套数组

javascript - javascript中for循环中的匿名回调函数

node.js - 导出模型函数时出现问题(Express 和 Mongoose)