【问题标题】:How to change type of a field in mongo db collection如何更改mongodb集合中字段的类型
【发布时间】:2014-02-20 13:23:06
【问题描述】:

我在名为 Orders 的数据库集合中插入了一些数据。我有一个名为numberofh 的字段。

但我的集合中的所有字段都是字符串类型。我已连接到服务器上的 mongo db shell,我想删除所有 numberofh 小于 5 的订单。

db.orders.remove({numberofh:{$lt:20}}) 不起作用,因为 numberofh 是一个字符串,所以 $lt 不起作用。

我可以通过其他方式,例如sdb.orders.remove({parseInt(numberofh}:{$lt:20})吗?

【问题讨论】:

    标签: mongodb shell database


    【解决方案1】:

    您不能在 mongoDB 中将字符串与数字进行比较。您必须首先插入一个新字段,即numberofh 的数字表示。你必须在客户端进行转换。不可能根据另一个字段的值创建一个字段。

    db.orders.find( {} ).forEach( function (x) {   
        x.numberofh_n = parseInt( x.numberofh, 10 ); 
        db.orders.save( x );
    });
    

    之后,您可以通过新字段删除记录:

    db.orders.remove( { numberofh_n: { $lt:20 } } )
    

    【讨论】:

    • 如果更改不会破坏应用程序中的某些其他功能,这将比我的解决方案更可取。对于我的情况,这样的事情是不可行的,因为其他进程需要某种格式的文档......
    • 您的代码中有复制意大利面错误...sdb => db
    • @heinob 这工作得很好。但它只改变一次,我需要再做一次,我可以创建那个永远存在的字段吗?
    • @user3332859:您无法自动为每个新文档创建字段。最好是,如果您在自己创建每个新文档时手动创建它。如果这是不可能的 --> 是的,你必须一遍又一遍地这样做:-(
    【解决方案2】:

    我认为您需要遍历每个文档并在光标到达时转换每个值:

    db.orders.find().forEach( function( doc ) {  
      // Extract the relevant value and convert to an int
      var numberofh_int = parseInt( doc[ "numberofh" ], 10 );
      // Perform conditionals on the value
      if ( numberofh_int < 20 ){ // $lt:20
        // Remove the document if it answers to the conditions
        db.orders.remove( doc );
      }
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多