Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在MongoDB中更改日期和时间?_Mongodb_Database - Fatal编程技术网

如何在MongoDB中更改日期和时间?

如何在MongoDB中更改日期和时间?,mongodb,database,Mongodb,Database,我有带姓名和日期的数据库。我需要将旧日期改为3天后的日期。例如,旧版本为2015年2月1日,新版本为2015年2月3日。 我只是想为所有的文件设定一个日期,但这意味着所有的考试都将在一天内完成 $db.getCollection('school.exam').update({},{$set:{“oldDay”:新ISODate(“2016-01-11T03:34:54Z”)},true,true) 问题只是用一些随机日期替换旧日期。因为MongoDB还不支持操作符在日期上应用(查看该上的JIRA

我有带姓名和日期的数据库。我需要将旧日期改为3天后的日期。例如,旧版本为2015年2月1日,新版本为2015年2月3日。 我只是想为所有的文件设定一个日期,但这意味着所有的考试都将在一天内完成

$db.getCollection('school.exam').update({},{$set:{“oldDay”:新ISODate(“2016-01-11T03:34:54Z”)},true,true)


问题只是用一些随机日期替换旧日期。

因为MongoDB还不支持操作符在日期上应用(查看该上的JIRA票证),作为增加日期字段的替代方法,您需要在循环中使用方法迭代方法返回的游标 获取将旧日期字段转换为时间戳,将以毫秒为单位的天数添加到时间戳中,然后使用操作符更新该字段

利用进行批量更新,这样可以提供更好的性能,因为您将以成批的方式(例如1000次)向服务器发送操作,这样可以提供更好的性能,因为您不是每1000次请求中就向服务器发送一次请求

下面演示了这种方法,第一个示例使用MongoDB版本
=2.6和<3.2
中提供的批量API。它更新了所有内容 在“日期”字段中添加3天,以删除集合中的文档:

var bulk = db.getCollection("school.exam").initializeUnorderedBulkOp(),
    counter = 0,
    daysInMilliSeconds = 86400000,
    numOfDays = 3;

db.getCollection("school.exam").find({ "oldDay": { $exists : true, "$type": 2 }}).forEach(function (doc) {
    var incDate = new Date(doc.oldDay.getTime() + (numOfDays * daysInMilliSeconds ));
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "oldDay": incDate }
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.getCollection('school.exam').initializeUnorderedBulkOp();
    }
})

if (counter % 1000 != 0) { bulk.execute(); }
下一个示例适用于新的MongoDB版本
3.2
,该版本自发布以来一直,并使用提供了一组更新的API:

var bulkOps = [],
    daysInMilliSeconds = 86400000,
    numOfDays = 3;

db.getCollection("school.exam").find({ "oldDay": { $exists : true, "$type": 2 }}).forEach(function (doc) { 
    var incDate = new Date(doc.oldDay.getTime() + (numOfDays * daysInMilliSeconds ));
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "oldDay": incDate } } 
            }         
        }           
    );     
})

db.getCollection("school.exam").bulkWrite(bulkOps, { 'ordered': true });

我的理解是否正确:您想在每个文档的日期上增加3天@是的,没错。对不起,我的问题不太清楚。