如何将 MongoDB 中的属性从文本类型转换为日期类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2900674/
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 do I convert a property in MongoDB from text to date type?
提问by Jeff Fritz
In MongoDB, I have a document with a field called "ClockInTime"
that was imported from CSV as a string.
在 MongoDB 中,我有一个包含"ClockInTime"
从 CSV 导入为字符串的字段的文档。
What does an appropriate db.ClockTime.update()
statement look like to convert these text based values to a date datatype?
db.ClockTime.update()
将这些基于文本的值转换为日期数据类型的适当语句是什么样的?
回答by kristina
This code should do it:
这段代码应该这样做:
> var cursor = db.ClockTime.find()
> while (cursor.hasNext()) {
... var doc = cursor.next();
... db.ClockTime.update({_id : doc._id}, {$set : {ClockInTime : new Date(doc.ClockInTime)}})
... }
回答by Ciges
I have exactly the same situation as Jeff Fritz.
我和杰夫弗里茨的情况完全一样。
In my case I have succeed with the following simpler solution:
就我而言,我使用以下更简单的解决方案取得了成功:
db.ClockTime.find().forEach(function(doc) {
doc.ClockInTime=new Date(doc.ClockInTime);
db.ClockTime.save(doc);
})
回答by Salil Panikkaveettil
This is a generic sample code in python using pymongo
这是在 python 中使用 pymongo 的通用示例代码
from pymongo import MongoClient
from datetime import datetime
def fixTime(host, port, database, collection, attr, date_format):
#host is where the mongodb is hosted eg: "localhost"
#port is the mongodb port eg: 27017
#database is the name of database eg : "test"
#collection is the name of collection eg : "test_collection"
#attr is the column name which needs to be modified
#date_format is the format of the string eg : "%Y-%m-%d %H:%M:%S.%f"
#http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
client = MongoClient(host, port)
db = client[database]
col = db[collection]
for obj in col.find():
if obj[attr]:
if type(obj[attr]) is not datetime:
time = datetime.strptime(obj[attr],date_format)
col.update({'_id':obj['_id']},{'$set':{attr : time}})
for more info : http://salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo
更多信息:http: //salilpa.com/home/content/how-convert-property-mongodb-text-date-type-using-pymongo
回答by webDEVILopers
If you need to check if the field already has been converted you can use this condition:
如果您需要检查该字段是否已被转换,您可以使用以下条件:
/usr/bin/mongo mydb --eval 'db.mycollection.find().forEach(function(doc){
if (doc.date instanceof Date !== true) {
doc.date = new ISODate(doc.date);
db.mycollection.save(doc);
}
});'
Otherwise the command line may break.
否则命令行可能会中断。
回答by Xavier Guihot
Starting Mongo 4.x
:
开始Mongo 4.x
:
db.collection.update()
can accept an aggregation pipeline, finally allowing the update of a field based on its current value (Mongo 4.2+
).- There is a new
$toDate
aggregation operator (Mongo 4.0
).
db.collection.update()
可以接受聚合管道,最终允许基于其当前值 (Mongo 4.2+
)更新字段。- 有一个新的
$toDate
聚合运算符 (Mongo 4.0
)。
Such that:
这样:
// { a: "2018-03-03" }
db.collection.update(
{},
[{ $set: { a: { $toDate: "$a" } } }],
{ multi: true }
)
// { a: ISODate("2018-03-03T00:00:00Z") }
The first part
{}
is the match query, filtering which documents to update (in this case all documents).The second part
[{ $set: { a: { $toDate: "$a" } } }]
is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline).$set
is a new aggregation operator which in this case replaces the field's value. The replaced value being the field itself concerted to anISODate
object. Note howa
is modified directly based on its own value ($a
).Don't forget
{ multi: true }
, otherwise only the first matching document will be updated.
第一部分
{}
是匹配查询,过滤要更新的文档(在本例中为所有文档)。第二部分
[{ $set: { a: { $toDate: "$a" } } }]
是更新聚合管道(注意方括号表示使用聚合管道)。$set
是一个新的聚合运算符,在这种情况下替换字段的值。被替换的值是与ISODate
对象一致的字段本身。请注意如何a
直接根据其自身的值 ($a
) 进行修改。不要忘记
{ multi: true }
,否则只会更新第一个匹配的文档。