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

use*_*257 28 mongodb mongodb-query aggregation-framework

有没有办法使用mongodb shell使用自定义格式将字符串转换为日期

我想转换"21/May/2012:16:35:33 -0400"到目前为止,

有没有办法通过DateFormatter或某事 Date.parse(...)ISODate(....)方法?

Cig*_*ges 37

在我的情况下,我成功使用以下解决方案将ClockTime集合中的字段ClockInTime 从字符串转换为Date类型:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })
Run Code Online (Sandbox Code Playgroud)

  • 我使用了``new ISODate(...)`作为我拥有的日期字符串,它运行得很好.谢谢你的建议. (6认同)

chr*_*dam 18

使用MongoDB 4.0和更新版本

$toDate运营商将值转换为日期.如果该值无法转换为日期,则会$toDate出错.如果值为null或缺少,则$toDate返回null:

您可以在聚合管道中使用它,如下所示:

db.collection.aggregate([
    { "$addFields": {
        "created_at": {
            "$toDate": "$created_at"
        }
    } }
])
Run Code Online (Sandbox Code Playgroud)

以上相当于使用$convert运算符如下:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$convert": { 
                "input": "$created_at", 
                "to": "date" 
            } 
        }
    } }
])
Run Code Online (Sandbox Code Playgroud)

使用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 */
            } 
        }
    } }
])
Run Code Online (Sandbox Code Playgroud)

使用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)}}
    ) 
};
Run Code Online (Sandbox Code Playgroud)

为了提高性能,尤其是在处理大型集合时,请利用批量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 queue
if (counter % 1000 != 0) { bulk.execute(); }
Run Code Online (Sandbox Code Playgroud)

使用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);
Run Code Online (Sandbox Code Playgroud)

  • 同样,使用$ dateFromString时,根据文档,格式字段可从版本4.0开始使用。我在3.6.5上尝试过,但出现错误“ $ dateFromString的无法识别参数:format” (3认同)

Mar*_*ick 9

您可以在Ravi Khakhkhar提供的第二个链接中使用javascript,或者您将不得不执行一些字符串操作来转换您的原始字符串(因为您原始格式中的某些特殊字符未被识别为有效的分隔符)但一旦你这样做,你可以使用"新"

training: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")
Run Code Online (Sandbox Code Playgroud)

这里有一些你可能会觉得有用的链接(关于修改mongo shell中的数据) -

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