简体   繁体   English

MongoDB更改字段类型

[英]Mongodb change field type

I had the problem with my query. 我的查询有问题。 How can I do something like this SQL query in mongoDB query? 我如何在mongoDB查询中执行类似此SQL查询的操作?

SELECT convert(datetime, field1)
FROM MyTable

Basicly you cannot do it. 基本上你做不到。 While you cannot reference back a value inside a query you cannot convert it on the fly. 尽管您无法在查询中引用回值,但无法即时对其进行转换。 You can update with a certain value if you know what you likely to put in. There is no such thing: 如果您知道可能要放入的内容,则可以使用某个值进行更新。没有这样的事情:

db.collection.update({},{$set:{b:ISODate('$b')}})

This is a current enhancement request. 这是当前的增强要求。

The only way is to write a script which crawl through the collection save docs with the updated type . 唯一的方法是编写一个脚本,该脚本会爬过具有更新类型的集合保存文档。 You also can run query based on the type of a field which may help if your flow brakes in between. 您还可以基于字段的类型运行查询,这可能在中间流程中断时有所帮助。

For this solution check that question : MongoDB: How to change the type of a field? 对于此解决方案,请检查以下问题: MongoDB:如何更改字段的类型?

The solution there is something like : 解决方案是这样的:

db.collection.find().forEach( function (x) {   
  x.b = new ISODate(x.b); // convert field to ISODate
  db.collection.save(x);
});

You can't. 你不能 If you need to convert a value stored in MongoDB, the only way to do it is in your application code. 如果您需要转换存储在MongoDB中的值,那么唯一的方法就是在您的应用程序代码中。 If this is a conversion that you need to do often and/or if you need to run queries on the converted values, you should consider storing both the original value and the converted value in the document. 如果这是您需要经常进行的转换和/或需要对转换后的值运行查询,则应考虑将原始值转换后的值都存储在文档中。 Denormalizations like this are very common in MongoDB schema design. 这样的非规范化在MongoDB模式设计中非常普遍。

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

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