如何更改字段的类型? [英] How to change the type of a field?
问题描述
我正在尝试从mongo shell中更改字段的类型.
I am trying to change the type of a field from within the mongo shell.
我正在这样做...
db.meta.update(
{'fields.properties.default': { $type : 1 }},
{'fields.properties.default': { $type : 2 }}
)
但是它不起作用!
推荐答案
更改数据$type
的唯一方法是在数据具有正确类型的情况下对数据执行更新.
The only way to change the $type
of the data is to perform an update on the data where the data has the correct type.
In this case, it looks like you're trying to change the $type
from 1 (double) to 2 (string).
因此,只需从数据库中加载文档,执行转换(new String(x)
),然后再次保存文档即可.
So simply load the document from the DB, perform the cast (new String(x)
) and then save the document again.
如果您需要完全从Shell中以编程方式进行此操作,则可以使用find(...).forEach(function(x) {})
语法.
If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {})
syntax.
针对下面的第二条评论.将字段bad
从数字更改为集合foo
中的字符串.
In response to the second comment below. Change the field bad
from a number to a string in collection foo
.
db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
这篇关于如何更改字段的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!