1

I have a MongoDB collection with many records like this

{ 
"_id" : "500cecd97f3b198ba7aceea3",
        "startDate" : NumberLong("1343023785531"),
        "user_id" : "soggettoDGcfe",
        "app_source" : "Diary",
        "measuredValue":120,
}

The problem is that due to a bug of an application, there are hundreds of records with the field "measuredValue" as a string:

{ 
"_id" : "ab0cecd97f3176eba7aceea3",
        "startDate" : NumberLong("1343023785531"),
        "user_id" : "soggettoDGcfe",
        "app_source" : "Diary",
        "measuredValue":"76.0",
}

So when i try to run some queries to check if the value is bigger than something, the record is not returned. With a query i was able to correct some records one by one

db.OBSERVABLEPARAMETER.update({_id:"500cecd97f3b198ba7aceea3"},{$set:{measuredValue:76}});

but they are hundreds! How can i update all of them rapidly?

4

1 回答 1

3

如果所有值都相同(即“76.0”),那么您只需执行以下操作:

db.OBSERVABLEPARAMETER.update({measuredValue:"76.0"},{$set:{measuredValue:76.0}}, {multi:true});

如果这些值都是不同的字符串,那么您将不得不使用以下命令查找不正确的字符串:

c = db.OBSERVABLEPARAMETER;
c.find({measuredValue:{$type: 2}}).forEach(function (r){
    c.update({_id:r._id},{$set:{measuredValue:Number(r.measuredValue)}});
});

如果您有大量测量值但测量值数量有限,则使用聚合框架获取所有单个值然后批量更新它们可能会更快。

于 2013-05-27T15:35:52.973 回答