为了账号安全,请及时绑定邮箱和手机立即绑定

在MongoDB中将字符串转换为日期

在MongoDB中将字符串转换为日期

qq_遁去的一_1 2019-09-26 09:58:50
有没有办法使用mongodb shell使用自定义格式将字符串转换为日期我正在尝试将“ 21 / May / 2012:16:35:33 -0400”转换为日期,有没有办法传递DateFormatter某种东西 Date.parse(...)或ISODate(....)方法?
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

使用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 and < 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)}}
    ) };

为了提高性能(尤其是在处理大型集合时),请充分利用Bulk API进行批量更新,因为您将批量操作(例如1000)发送到服务器,这将为您带来更好的性能,因为您不会将每个请求都发送给服务器。服务器,每1000个请求中只有一次。

下面演示了这种方法,第一个示例使用MongoDB版本中可用的Bulk API >= 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 queueif (counter % 1000 != 0) { bulk.execute(); }

使用MongoDB 3.2

下一个示例适用于新的MongoDB版本3.2,此版本已弃用Bulk 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);


查看完整回答
1 反对 回复 2019-09-26
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

就我而言,以下解决方案已成功完成,该解决方案将ClockTime集合中的字段ClockInTime 从字符串转换为Date类型

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })


查看完整回答
反对 回复 2019-09-26
  • 3 回答
  • 0 关注
  • 5833 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信