【问题标题】:How to convert string to boolean in MongoDB?如何在 MongoDB 中将字符串转换为布尔值?
【发布时间】:2018-06-28 05:10:06
【问题描述】:
我是 mongo 的新手,如果这是一个无聊的问题,请原谅。我错误地用“true”/“false”(类型字符串)更新了 mongo 中的特定标志。我想要一个查询,以便我可以更新我的集合并将标志的类型从字符串“true”更改为布尔值 true。
例子:
{flag: "true"} to { flag : true}
所以我有两个问题:
- 我可以通过查询来做到这一点吗?
- 如果可以,怎么做?
【问题讨论】:
标签:
mongodb
mongodb-query
【解决方案1】:
对于相对较小的集合,如果字段类型为字符串,则执行更新:
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); }
【解决方案2】:
只需调用这两个查询:
db.coll.update({
flag: "true"
}, {
$set: {flag: true}
}, { multi: true })
db.coll.update({
flag: "false"
}, {
$set: {flag: false}
}, { multi: true })
第一个将所有"true" 更改为true,第二个你会得到它。
对于中/大型集合,这将比已经建议的 foreach 声明快得多。
【解决方案4】:
在 MongoDB v4.0 中,可以使用 $toBool 运算符将字符串转换为布尔值。在这种情况下
db.col.aggregate([
{
$project: {
_id: 0,
flagBool: { $toBool: "$flag" }
}
}
])
输出:
{ "flagBool" : true }