mongodb 如何更新 mongo 控制台中的日期字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8821206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update date field in mongo console?
提问by Bdfy
For example I want to update all records to '2012-01-01' ( "time" : ISODate("2011-12-31T13:52:40Z") ).
例如,我想将所有记录更新为“2012-01-01”(“时间”:ISODate(“2011-12-31T13:52:40Z”))。
db.test.update( { time : '2012-01-01' }, false, true )
return error:
返回错误:
Assert failed : need an object
Error("Printing Stack Trace")@:0
()@shell/utils.js:35
("assert failed : need an object")@shell/utils.js:46
(false,"need an object")@shell/utils.js:54
([object Object],false,true)@shell/collection.js:189
@(shell):1
Wed Jan 11 17:52:35 uncaught exception: assert failed : need an object
回答by mnemosyn
You need to create a new ISODate
object like this:
您需要ISODate
像这样创建一个新对象:
db.test.insert({"Time" : new ISODate("2012-01-10") });
This is true both for updates and for queries. Note that your query syntax is incorrect, it should be
对于更新和查询都是如此。请注意,您的查询语法不正确,应该是
db.test.update({ criteria }, { newObj }, upsert, multi);
For example, to update all objects, consider
例如,要更新所有对象,请考虑
db.test.update( {}, { $set : { "time" : new ISODate("2012-01-11T03:34:54Z") } }, true, true);
Also note that this is very different from
另请注意,这与
db.test.update( {}, { "time" : new ISODate("2012-01-11T03:34:54Z") }, true, false);
because the latter will replacethe object, rather than add a new field to the existing document or updating the existing field. In this example, I changed the last parameter to false
, because multi updates only work with $
operators.
因为后者将替换对象,而不是向现有文档添加新字段或更新现有字段。在此示例中,我将最后一个参数更改为false
,因为多重更新仅适用于$
运算符。
回答by webDEVILopers
If you need to convert an existing date field (imported from MySQL format 'yyyy-mm-dd' f.e.) to ISODate you can loop through the documents this way:
如果您需要将现有日期字段(从 MySQL 格式 'yyyy-mm-dd' fe 导入)转换为 ISODate,您可以通过以下方式遍历文档:
/usr/bin/mongo yourdbname --eval "db.yourcollectionname.find().forEach(function(doc){doc.yourdatefield = new ISODate(doc.yourdatefield);db.yourcollectionname.save(doc)});"
回答by Salvador Dali
You can do this in the old-school way by creating ISO date
您可以通过创建 ISO 日期以传统方式执行此操作
db.test.update({_id : 1}, {
$set : {
"time" : new ISODate("your current date")
}
});
But note that with new Mongo 2.6
you will be able to update date to a current date really easy with $currentDate.
但请注意,使用 newMongo 2.6
您将能够使用$currentDate非常轻松地将日期更新为当前日期。
db.test.update( { _id: 1 }, {
$currentDate: {
time: true,
},
})