有没有一种方法可以在MongoDB Shell中使用自定义格式将字符串转换为日期?
我正在尝试将“21/May/2012:16:35:33 -0400”转换为日期,
是否有办法将DateFormatter
或其他内容传递给Date.parse(...)
或ISODate(....)
方法?
有没有一种方法可以在MongoDB Shell中使用自定义格式将字符串转换为日期?
我正在尝试将“21/May/2012:16:35:33 -0400”转换为日期,
是否有办法将DateFormatter
或其他内容传递给Date.parse(...)
或ISODate(....)
方法?
使用 MongoDB 4.0 及更高版本
$toDate
运算符将值转换为日期。如果无法将值转换为日期,则 $toDate
会出现错误。 如果值为 null 或缺失,则 $toDate
返回 null:
您可以在聚合管道中使用它,如下所示:
db.collection.aggregate([
{ "$addFields": {
"created_at": {
"$toDate": "$created_at"
}
} }
])
上述代码等同于使用$convert
运算符,如下所示:
db.collection.aggregate([
{ "$addFields": {
"created_at": {
"$convert": {
"input": "$created_at",
"to": "date"
}
}
} }
])
使用MongoDB 3.6及更高版本
您还可以使用$dateFromString
运算符,将日期/时间字符串转换为日期对象,并具有指定日期格式和时区的选项:
db.collection.aggregate([
{ "$addFields": {
"created_at": {
"$dateFromString": {
"dateString": "$created_at",
"format": "%m-%d-%Y" /* <-- option available only in version 4.0. and newer */
}
}
} }
])
使用MongoDB版本>= 2.6且<3.2
如果MongoDB版本没有原生运算符来进行转换,您需要手动迭代由find()
方法返回的游标,可以使用forEach()
方法或游标方法next()
访问文档。在循环内部,将字段转换为ISODate对象,然后使用$set
运算符更新字段,如下例所示,其中字段称为created_at
,当前以字符串格式保存日期:
var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});
while (cursor.hasNext()) {
var doc = cursor.next();
db.collection.update(
{"_id" : doc._id},
{"$set" : {"created_at" : new ISODate(doc.created_at)}}
)
};
为了在处理大量数据时实现更好的性能,特别是在进行批量更新操作时,建议使用MongoDB提供的Bulk API。这样你可以将操作分为一批一批的,比如每1000个操作一批发送到服务器上,从而提高性能,因为你不需要将每个请求都发送到服务器上,只需每1000个请求发送一次即可。>= 2.6 and < 3.2
中更新一个集合中的所有文档,将它们的created_at
字段更改为日期类型:var bulk = db.collection.initializeUnorderedBulkOp(),
counter = 0;
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new ISODate(doc.created_at);
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "created_at": newDate}
});
counter++;
if (counter % 1000 == 0) {
bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }
使用MongoDB 3.2
下一个例子适用于新的MongoDB版本3.2
,此版本已经弃用了批量API,并提供了一组更新的API,使用了bulkWrite()
方法:
var bulkOps = [],
cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});
cursor.forEach(function (doc) {
var newDate = new ISODate(doc.created_at);
bulkOps.push(
{
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "created_at": newDate } }
}
}
);
if (bulkOps.length === 500) {
db.collection.bulkWrite(bulkOps);
bulkOps = [];
}
});
if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps);
$dateFromString
仅适用于 MongoDB 3.6
或更高版本,而不是您所写的 3.4.4
。我在 3.4.10
上尝试了一下,但它没有起作用... - SimonSimCity在我的案例中,我成功地使用以下解决方案,将ClockTime集合中的ClockInTime字段从字符串转换为日期类型:
db.ClockTime.find().forEach(function(doc) {
doc.ClockInTime=new Date(doc.ClockInTime);
db.ClockTime.save(doc);
})
new Date(...)
弄乱了我的日期。new ISODate(...)
可以工作。谢谢 @sumitkm - Tur1ngtraining:PRIMARY> Date()
Fri Jun 08 2012 13:53:03 GMT+0100 (IST)
training:PRIMARY> new Date()
ISODate("2012-06-08T12:53:06.831Z")
training:PRIMARY> var start = new Date("21/May/2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012 16:35:33 -0400") => works
training:PRIMARY> start
ISODate("2012-05-21T20:35:33Z")
http://cookbook.mongodb.org/patterns/date_range/
http://www.mongodb.org/display/DOCS/Dates
http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell
我发现最容易使用$toDate运算符与updateMany相结合。
db.collection.updateMany({}, [{$set: {createdAt: {$toDate: "$createdAt"}}}]);
我需要将MongoDB储存的一些字符串重新格式化为合适且有效的日期时间字段。
以下是特殊日期格式的代码: "2014-03-12T09:14:19.5303017+01:00"
但您可以轻松地采用这种思路,并编写自己的正则表达式来解析日期格式:
// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;
db.Product.find().forEach(function(doc) {
var matches = myregexp.exec(doc.metadata.insertTime);
if myregexp.test(doc.metadata.insertTime)) {
var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
var hours = matches[4]-(-offset)+1
var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
print("succsessfully updated");
} else {
print("not updated");
}
})
你可以像这样编写脚本,使用类似momentjs的库:
[install_moment.js]
function get_moment(){
// shim to get UMD module to load as CommonJS
var module = {exports:{}};
/*
copy your favorite UMD module (i.e. moment.js) here
*/
return module.exports
}
//load the module generator into the stored procedures:
db.system.js.save( {
_id:"get_moment",
value: get_moment,
});
然后在命令行中像这样加载脚本:
> mongo install_moment.js
// LOAD STORED PROCEDURES
db.loadServerScripts();
// GET THE MOMENT MODULE
var moment = get_moment();
// parse a date-time string
var a = moment("23 Feb 1997 at 3:23 pm","DD MMM YYYY [at] hh:mm a");
// reformat the string as you wish:
a.format("[The] DDD['th day of] YYYY"): //"The 54'th day of 1997"