简体   繁体   English

如何在MongoDB中高效地更新集合字段?

[英]How to update a field of collection efficient in MongoDB?

I have dataset as 我有数据集

{"id":1,"Timestamp":"Mon, 11 May 2015 07:57:46 GMT","brand":"a"}
{"id":2,"Timestamp":"Mon, 11 May 2015 08:57:46 GMT","brand":"a"}

The expected result of data is 数据的预期结果是

{"id":1,"Timestamp":ISODate("2015-05-11T07:57:46Z"),"brand":"a"}
{"id":2,"Timestamp":ISODate("2015-05-11T08:57:46Z"),"brand":"b"}

It means I want to revise the Timestamp in each row from string to ISODate My current code is 这意味着我想将每行中的时间戳从字符串修改为ISODate我当前的代码是

db.tmpAll.find().forEach(
    function (a) {
        a.Timestamp = new Date(a.Timestamp);
        db.tmpAll2.insert(a);
    }
);

It runs sucessfully, but it will take couple minutes to run the code and it need to create a new collection. 它可以成功运行,但是需要花费几分钟才能运行代码,并且需要创建一个新集合。 Is there any efficient way to do it? 有什么有效的方法吗?

You don't need to create new collection. 您无需创建新集合。 Use the collection.save method to update your document. 使用collection.save方法更新您的文档。

db.tmpAll.find().forEach(function(doc){
    doc.Timestamp = new Date(doc.Timestamp); 
    db.tmpAll.save(doc); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM