Vai*_*gon 6 mongodb mongodb-query
我是mongo的新手,请原谅我,如果这是一个noobish问题.我错误地使用"true"/"false"(类型字符串)更新了mongo中的特定标志.我想要一个查询,以便我可以更新我的集合并将标志的类型从字符串"true"更改为布尔值true.
例:
{flag: "true"} to { flag : true}
Run Code Online (Sandbox Code Playgroud)
所以我有两个问题:
只需调用这两个查询:
db.coll.update({
flag: "true"
}, {
$set: {flag: true}
}, { multi: true })
db.coll.update({
flag: "false"
}, {
$set: {flag: false}
}, { multi: true })
Run Code Online (Sandbox Code Playgroud)
第一个全部更改"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);
});
Run Code Online (Sandbox Code Playgroud)
对于中/大型馆藏,您可以将bulkWriteAPI用作
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); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3943 次 |
| 最近记录: |