2014-02-20 44 views
1

我在名为Orders的数据库集合中插入了一些数据。我有一个名为numberofh的字段。如何更改mongo db集合中字段的类型

但我收集的所有字段都是字符串类型。我连接到服务器上的数据库蒙戈外壳和我想删除所有的订单,其中numberofh是小于5

db.orders.remove({numberofh:{$lt:20}})不起作用,因为numberofh是一个字符串,因此$lt将无法​​正常工作。

我可以这样做一些其他方式,如sdb.orders.remove({parseInt(numberofh}:{$lt:20})

回答

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 } }) 
+0

这将是最好我的解决方案,如果变化不破在应用一些其他功能。像这样的东西对我的情况来说是不可行的,因为其他进程需要某种格式的文档... – Lix

+0

您在代码中有一个副本面食错误...'sdb => db' – Lix

+0

@heinob这工作得很好。但是它的变化只有一次,我需要再做一次,我能创造这个领域永远在那里吗? – user3332859

1

我认为你需要为光标到达它遍历每个文档和转换每个值:

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); 
    } 
});