Mongo:如何使用long timeStamp将所有条目转换为ISODate?

时间:2015-07-20 14:52:51

标签: mongodb date type-conversion isodate

我有一个当前的Mongo数据库,其中包含累积的条目/字段

{
 name: "Fred Flintstone",
 age : 34,
 timeStamp : NumberLong(14283454353543)
}

{
 name: "Wilma Flintstone",
 age : 33,
 timeStamp : NumberLong(14283454359453)
}

等等......

问题:我想将数据库中的所有条目转换为相应的ISODate - 如何做到这一点?

期望的结果:

{
 name: "Fred Flintstone",
 age : 34,
 timeStamp : ISODate("2015-07-20T14:50:32.389Z")
}

{
 name: "Wilma Flintstone",
 age : 33,
 timeStamp : ISODate("2015-07-20T14:50:32.389Z")
}

我尝试过的事情

 >db.myCollection.find().forEach(function (document) {
    document["timestamp"] = new Date(document["timestamp"])

    //Not sure how to update this document from here
    db.myCollection.update(document) //?
})

2 个答案:

答案 0 :(得分:6)

你几乎就在那里,你只需要在修改过的文档上调用save()方法来更新它,因为该方法使用 insert update 命令。在上面的示例中,文档包含_id字段,因此save()方法等同于 update() 操作,其中up​​sert选项设置为true并且查询_id字段上的谓词:

db.myCollection.find().snapshot().forEach(function (document) {
    document["timestamp"] = new Date(document["timestamp"]);
    db.myCollection.save(document)
})

以上内容类似于您之前尝试过的明确调用 update() 方法:

db.myCollection.find().snapshot().forEach(function (document) {
    var date = new Date(document["timestamp"]);
    var query = { "_id": document["_id"] }, /* query predicate */
        update = { /* update document */
           "$set": { "timestamp": date }
        },
        options = { "upsert": true };         

    db.myCollection.update(query, update, options);
})

对于相对较大的集合大小,您的数据库性能会很慢,建议您使用mongo bulk updates

MongoDB版本> = 2.6和< 3.2:

var bulk = db.myCollection.initializeUnorderedBulkOp(),
    counter = 0;

db.myCollection.find({"timestamp": {"$not": {"$type": 9 }}}).forEach(function (doc) {    
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "timestamp": new Date(doc.timestamp") } 
    });

    counter++;
    if (counter % 1000 === 0) {
        // Execute per 1000 operations 
        bulk.execute(); 

        // re-initialize every 1000 update statements
        bulk = db.myCollection.initializeUnorderedBulkOp();
    }
})

// Clean up remaining operations in queue
if (counter % 1000 !== 0) bulk.execute(); 

MongoDB版本3.2及更新版本:

var ops = [],
    cursor = db.myCollection.find({"timestamp": {"$not": {"$type": 9 }}});

cursor.forEach(function (doc) {     
    ops.push({ 
        "updateOne": { 
            "filter": { "_id": doc._id } ,              
            "update": { "$set": { "timestamp": new Date(doc.timestamp") } } 
        }         
    });

    if (ops.length === 1000) {
        db.myCollection.bulkWrite(ops);
        ops = [];
    }     
});

if (ops.length > 0) db.myCollection.bulkWrite(ops);

答案 1 :(得分:0)

当尝试从NumberLong值实例化Date对象时,似乎在mongo中发生了一些繁琐的事情。主要是因为NumberLong值被转换为错误的表示,并且使用回退到当前日期。

我和mongo战斗了2天,最后我找到了解决方案。关键是将NumberLong转换为Double ...并将double值传递给Date构造函数。

以下是使用灯泡操作并为我工作的解决方案......

(lastIndexedTimestamp是迁移到ISODate并存储在lastIndexed字段中的集合字段。创建临时集合,并在最后将其重命名为原始值。)

db.annotation.aggregate(    [
     { $project: { 
        _id: 1,
        lastIndexedTimestamp: 1,
        lastIndexed: { $add: [new Date(0), {$add: ["$lastIndexedTimestamp", 0]}]}
        }
    },
    { $out : "annotation_new" }
])

//drop annotation collection
db.annotation.drop();

//rename annotation_new to annotation
db.annotation_new.renameCollection("annotation");