我有一个包含以下文档的收藏集:
{ 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
}
猫鼬怎么可能?
答案 0 :(得分:0)
我将假设每个用户只会有两个文档。如果您想计算每个用户超过两种类型的时间差,我的答案将有所不同。这些是我将要实现的步骤:
使用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。此程序从每名用户(以分钟为单位)使用不同类型的两个文档计算两个日期之间的绝对时差。如果要计算两种以上类型之间的时间差,则代码会稍微复杂一些。
答案 1 :(得分:0)
使用Subtract
减去两个数字以返回差值,或者减去两个日期以返回差值(以毫秒为单位),或者减去日期和一个数字(以毫秒为单位)以返回结果的日期。
{ $subtract: [ <expression1>, <expression2> ] }