这是一个小的更新脚本,用于在 MongoDB 中将那些讨厌的日期字符串转换为漂亮的日期时间:
var mmap = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06",
"Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};
db.foo.find().forEach(function(d) {
var zz = d['time'].split(' '); // ['Nov','26,','2021','15:06:30.092158000']
print(zz);
// Turns 4, into 04 and 27, into 27. Sort of like %02d:
var day = ("00" + zz[1].substring(0,zz[1].length-1) ).slice(-2)
var dd = new ISODate(zz[2] + '-' + mmap[zz[0]] + '-'
+ day
+ 'T' + zz[3].substring(0,12) // MongoDB can only store millis
+ 'Z');
// So as not to lose info, let's capture the nanos as an int:
var nanos = new NumberInt(zz[3].substring(9,18));
db.foo.update({_id:d['_id']},{$set: {"time":dd, "nanos":nanos}});
});
一旦你有了真正的约会,一切都会变得简单。这是一种基于某些过滤条件获取一组文档的通用方法,然后获取第一个和最后一个日期并找到差异。
db.foo.aggregate([
// Put $match and other filtering expressions here if desired.
{$sort: {"time":1}} // Get them in order...
// ... and take first and last items!
,{$group: {_id: null, fd: {$first:"$time"}, ld: {$last:"$time"}}}
,{$addFields: {diff: {$subtract: ["$ld","$fd"]}}}
]);