如何在 MongoDB 中将字符串转换为布尔值?

How to convert string to boolean in MongoDB?

我是 mongo 的新手,如果这是一个菜鸟问题,请原谅。我用 "true"/"false"(类型字符串)错误地更新了 mongo 中的特定标志。我想要一个查询,以便我可以更新我的集合并将标志的类型从字符串 "true" 更改为布尔值 true。

示例:

{flag: "true"} to { flag : true}

所以我有两个问题:

  1. 我可以通过查询来做到这一点吗?
  2. 如果可以,怎么做?

只需调用这两个查询:

db.coll.update({
   flag: "true"
}, {
   $set: {flag: true}
}, { multi: true })

db.coll.update({
   flag: "false"
}, {
   $set: {flag: false}
}, { multi: true })

第一个将所有 "true" 更改为 true,第二个你会得到它。

对于 medium/big 集合,这将 比已经建议的 foreach 语句 .

快得多

参见MongoDB Manual - Modify Documents。示例:

db.collectionName.update({_id: "yourid"}, {$set: {flag : true}})

对于相对较小的集合,如果字段类型为字符串,则执行更新:

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

对于 medium/large 集合,您可以使用 bulkWrite API as

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 }