在mongodb中将字符串更新为Date对象 [英] Update string to Date object in mongodb

查看:104
本文介绍了在mongodb中将字符串更新为Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究mongodb和node.js,遇到了一个场景.

I'm working on mongodb and node.js and i came a across a scenario.

我正在批量插入大约2亿条记录的数据.在这些字段中,有些字段另存为字符串,但实际上是日期.

I'm bulk inserting data around 200 million record. In those there are some fields that are saved as string but actually are date.

有什么办法可以做类似的事情

Is there any way where I can do something like

db.collection.update({}, {$set: {dateField: new Date(dateField)}}, { multi: true })

日期采用YYYY-MM-DD格式

推荐答案

使用4.2或更高版本的Modern MongoDB,您实际上可以在一条语句中完成此操作:

With a Modern MongoDB from version 4.2 or greater, you can actually do this in a single statement:

db.collection.updateMany(
  {},
  [{ "$set": { "dateField": { "$toDate": "$dateField" } }]
);

这依赖于在该版本上实现的新功能,该功能允许在语句中使用聚合表达式",该语句实际上可以访问文档的现有值并使用它们来产生新的输出.

This relies on a new feature implemented at that version which allows "aggregation expressions" to be used within a statement which can indeed access the existing values of a document and use them to produce new output.

在这种情况下, $set 用于将新内容与现有文档合并",然后[$toDate][2]处理转换.

In this case the $set is used to "merge" new content with the existing document and the [$toDate][2] handles the transformation.

MongoDB当前没有任何功能可让您在更新操作中访问另一个字段的内容.您可以使用任何一种语言进行的唯一操作就是迭代结果:

There is currently no feature in MongoDB that allows you to access the content of another field in an update operation. The only thing that you can do in any language for is iterate the results:

db.collection.find({}).forEach(function(doc) { 
    db.collection.update(
        { "_id": doc._id }, 
        {"$set": { "dateField": new Date(doc.dateField) }}
    );
});

现在,您可以使用 db.eval() 但要小心,因为有很多危险记录在案,并且可能会对生产系统产生很大的影响.

Now, you could run that on the server using db.eval() but beware as there are many dangers to this as documented, and it is likely to have a large impact on a production system.

无法通过其他选择来使您的更新以尽可能接近(就网络而言)运行的数据库为基础.

Failing that your other options are based on getting your update to run as close as possible (in network terms) to the database.

在您的最后著作中,确实出现了您的日期并非全部采用此处提到的格式,并且某些条目在月份或日期中只有一位数字.因此,如果您还没有的话,也将不得不对其进行处理.

Also on your last writings it did appear that you dates were not all in the format you mention here, and that some entries had only one digit in the month or day. So you will have to deal with that as well if you have not already.

这篇关于在mongodb中将字符串更新为Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆