Mongodb从现有文档更新时间戳到日期
我有这个MongoDB文档,我想将newDate更新为使用单个MongoDB查询的db中的timestamp值,如下所示Mongodb从现有文档更新时间戳到日期,mongodb,datetime,timestamp,mongodb-query,Mongodb,Datetime,Timestamp,Mongodb Query,我有这个MongoDB文档,我想将newDate更新为使用单个MongoDB查询的db中的timestamp值,如下所示 { "_id" : ObjectId("54ec60dae4b07e1ee10a899d"), "_class" : "com.lybrate.core.phoenix.event.PhxEventTracking", "rfpId" : "198163", "eventType" : "QnA", "eventId" : "49548
{
"_id" : ObjectId("54ec60dae4b07e1ee10a899d"),
"_class" : "com.lybrate.core.phoenix.event.PhxEventTracking",
"rfpId" : "198163",
"eventType" : "QnA",
"eventId" : "49548",
"paramType" : "S",
"timestamp" : NumberLong("1424777434982"),
"utm_source" : "email",
"utm_medium" : "gw",
"utm_content" : "null",
"utm_term" : "null",
"utm_campaign" : "Email_050215_gw_askq",
"referrer" : "https://www.lybrate.com/questions/ask",
"source" : "PS-AQP",
"e_stat" : "rejected ",
"a_time" : NumberLong("1424802600000"),
"newdDate" : ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ"),
"newDate" : ISODate("2015-03-27T08:32:31.679Z")
}
但这会将newDate更新为当前时间,而不是timestamp的dateTime值…请回答..谢谢并致意..:我已经仔细检查了代码的功能,当您传递this.timestamp参数时,这将引用与JavaScript中的窗口类似的全局范围 我还尝试在集合中插入随机元素,使用各种变量名而不是时间戳:
db.phxEventTracking.update({"eventType":"QnA"},{$set:{newDate:new ISODate(this.timestamp)}},{upsert:false,multi:true})
由于这些变量未定义,ISODate包装器解释没有传递任何参数,因此调用新的ISODate,返回当前时间戳
以下是mongo shell中记录的ISODate函数的代码:
db.test.insert({ date: new ISODate(this.variable1) });
db.test.insert({ date: new ISODate(this.variable2) });
function (isoDateStr){
if (!isoDateStr)
return new Date();
var isoDateRegex = /(\d{4})-?(\d{2})-?(\d{2})([T ](\d{2})(:?(\d{2})(:?(\d{2}(\.\d+)?))?)?(Z|([+-])(\d{2}):?(\d{2})?)?)?/;
var res = isoDateRegex.exec(isoDateStr);
if (!res)
throw "invalid ISO date";
var year = parseInt(res[1],10) || 1970; // this should always be present
var month = (parseInt(res[2],10) || 1) - 1;
var date = parseInt(res[3],10) || 0;
var hour = parseInt(res[5],10) || 0;
var min = parseInt(res[7],10) || 0;
var sec = parseInt((res[9] && res[9].substr(0,2)),10) || 0;
var ms = Math.round((parseFloat(res[10]) || 0) * 1000);
if (ms == 1000) {
ms = 0;
++sec;
}
if (sec == 60) {
sec = 0;
++min;
}
if (min == 60) {
min = 0;
++hour;
}
if (hour == 24) {
hour = 0; // the day wrapped, let JavaScript figure out the rest
var tempTime = Date.UTC(year, month, date, hour, min, sec, ms);
tempTime += 24 * 60 * 60 * 1000; // milliseconds in a day
var tempDate = new Date(tempTime);
year = tempDate.getUTCFullYear();
month = tempDate.getUTCMonth();
date = tempDate.getUTCDate();
}
var time = Date.UTC(year, month, date, hour, min, sec, ms);
if (res[11] && res[11] != 'Z'){
var ofs = 0;
ofs += (parseInt(res[13],10) || 0) * 60*60*1000; // hours
ofs += (parseInt(res[14],10) || 0) * 60*1000; // mins
if (res[12] == '+') // if ahead subtract
ofs *= -1;
time += ofs
}
return new Date(time);
}