1

我正在尝试以这种格式(YYYY-MM-DD)使用昨天日期更新 Mongo DB COllection

我正在尝试这种方式

var currentDate = new Date();
            currentDate.setDate(currentDate.getDate()-1);
            var month = (currentDate.getMonth() < 9 ? "0"+ (currentDate.getMonth()+1) : (currentDate.getMonth()+1));
            var day = (currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate());
            var date = currentDate.getTime();
            var patt = date;


    db.LoginCount.update({yesterday : {$exists : false}}, {$set: {yesterday : new Date(date)}})

我得到的输出是

 db.LoginCount.find().pretty()
{
        "yesterday" : ISODate("2013-05-01T03:25:28.640Z")
}

请告诉我如何更新 COllection 以便它以这种格式 YYYY-MM-DD 插入日期

4

2 回答 2

0

您的 $set 正在为昨天的字段值使用 Date 类型的值。这就是您的查找查询返回 ISODate 的原因。请参阅http://docs.mongodb.org/manual/core/document/

如果你真的需要昨天成为一个字符串,你将需要使用:{$set: {yesterday:currentDate.toISOString().substring(0,10)}}

如果要将日期存储为具有标准化时间组件(例如 00:00:00)的日期类型字段,请使用以下内容:

var d = new Date(Date) {$set {yesterday:new Date(Date.UTC(currentDate.getUTCFullYear(), currentDate.getUTCMonth(), currentDate.getUTCDate(), 0,0,0))}}

于 2013-05-02T05:15:23.887 回答
0

反正我是这样解决的

m = function() { emit(this.cust_id, 1); }

r = function (k, vals) { var sum = 0; for (var i in vals) { sum += vals[i]; } return sum; }

q = function() {
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate()-1);
    var month = (currentDate.getMonth() < 9 ? "0"+ (currentDate.getMonth()+1) : (currentDate.getMonth()+1));
    var day = (currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate());
    var date = currentDate.getTime();
    var patt = date;
    var query = {"created_at":"2013-04-30 11:19:52.587"};
    return query;
}

res = db.logins.mapReduce(m, r, { query : q(), out :  "LoginCount" });
var yesterday = new Date(Date.now() - 86400000);
db.LoginCount.update({yesterday : {$exists : false}}, {$set: {yesterday : yesterdayday}})
于 2013-05-02T05:53:09.513 回答