在javascript中增加日期,以便更新MongoDB

时间:2016-01-12 13:27:43

标签: javascript mongodb date

在MongoDB集合中,我有3个对象。我需要在每个对象中更新一个变量(日期类型)。主要任务是增加对象的日期。例如:所有对象都具有相同的变量:

"Time1" : ISODate("2016-01-12T21:37:46.738Z")

我的问题是用当前日期更新第一个对象,手动我这样做:

$db.getCollection('my.data')({'_id':ObjectId("52e637fca92cf1ec6a73c1e8")}, {$currentDate: {Time1: true}})

接下来是将第二个对象的日期增加1天,我的意思是用明天日期更新它。我无法通过shell执行此操作,因为$ inc不适用于Date类型。 所以,我迷失了javascript

我找到了如何使用java脚本获取它,但我不知道如何在一个脚本中收集所有内容。

var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以将 $set 运算符用于其他字段,以及更新对象中的 $currentDate 运算符:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);

var dayAfterTomorrow = new Date();
dayAfterTomorrow.setDate(dayAfterTomorrow.getDate()+2);

db.getCollection("my.data").update(
    { "_id": ObjectId("52e637fca92cf1ec6a73c1e8") },
    { 
        "$currentDate": { "Time1": true },
        "$set": {
            "Time2": tomorrow,
            "Time3": dayAfterTomorrow
        }
    }
)