如何更改字段的类型? [英] How to change the type of a field?

查看:45
本文介绍了如何更改字段的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从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.

在这种情况下,您似乎正在尝试更改$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屋!

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