我是mongo的新手,所以如果问题有点菜鸟请见谅。我错误地使用字符串类型的"true"/"false"更新了mongo中的特定标志。我想查询一下,以便我可以更新我的集合并将标志的类型从字符串"true"更改为布尔值true。
例如:
{flag: "true"} to { flag : true}
我有两个问题:
- 我能用查询来做到这一点吗?
- 如果可以,如何实现?
我是mongo的新手,所以如果问题有点菜鸟请见谅。我错误地使用字符串类型的"true"/"false"更新了mongo中的特定标志。我想查询一下,以便我可以更新我的集合并将标志的类型从字符串"true"更改为布尔值true。
例如:
{flag: "true"} to { flag : true}
我有两个问题:
只需调用这两个查询:
db.coll.update({
flag: "true"
}, {
$set: {flag: true}
}, { multi: true })
db.coll.update({
flag: "false"
}, {
$set: {flag: false}
}, { multi: true })
第一个将所有的"true"
更改为true
,第二个你会得到它。
对于中大型集合,这比已经建议的foreach
语句显着更快。
对于相对较小的集合,如果字段的类型为字符串,请执行更新:
db.collection.find({ "flag": { $type : 2 } }).forEach(function (doc){
var isTrueSet = (doc.flag === "true");
doc.flag = isTrueSet; // convert field to Boolean
db.collection.save(doc);
});
对于中等/大型集合,您可以使用bulkWrite
API。
var cursor = db.collection.find({ "flag": { "$exists": true, "$type": 2 } }),
ops = [];
cursor.forEach(function(doc){
var isTrueSet = (doc.flag === "true");
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "flag": isTrueSet } }
}
});
if (ops.length == 1000) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }
在MongoDB v4.0中,可以使用$toBool运算符将字符串转换为布尔值。在这种情况下
db.col.aggregate([
{
$project: {
_id: 0,
flagBool: { $toBool: "$flag" }
}
}
])
输出:
{ "flagBool" : true }