mongodb - 使用更新查询将文档值从字符串更改为 ObjectId

我需要将 mongodb 集合中所有文档的 Profession_id 的值从 string 更新为 ObjectId

我的收藏职业是(这里我只粘贴了 2 个文档,实际上我有超过 1 万个文档)

{
    "_id" : ObjectId("575845a713d284da0ac2ee81"),
    "Profession_id" : "575841b313d284da0ac2ee7d",
    "Prof_Name" : "Chief Officer"
}

{
    "_id" : ObjectId("575845d213d284da0ac2ee82"),
    "Profession_id" : "575841b313d284da0ac2ee7d",
    "Prof_Name" : "Executive Officer"
}

请帮助我如何更新 MongoDB 中的值。

最佳答案

我们需要遍历 snapshot()我们的文档并使用 $set 更新每个文档更新运算符。为此,我们使用批量操作来实现最高效率。

从 MongoDB 3.2 开始,我们需要使用 bulkWrite()方法

var requests = [];    
let cursor = db.collection.find({}, { "Profession_id": 1 }).snapshot();
cursor.forEach( document => { 
    requests.push( { 
        "updateOne": {
            "filter": { "_id": document._id },
            "update": { "$set": { "Profession_id": ObjectId(document.Profession_id) } }
        }
    });
    if (requests.length === 1000) {
        // Execute per 1000 operations and re-init
        db.collection.bulkWrite(requests);
        requests = [];
    }
});

// Clean up queues
if (requests.length > 0)
    db.collection.bulkWrite(requests);     

从 MongoDB 2.6 到 3.0,您需要使用现已弃用的 Bulk API 及其关联 method .

var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;

var cursor = db.collection.find({}, { "Profession_id": 1 }).snapshot()

cursor.forEach(function(document) { 
    bulk.find( { "_id": document._id } ).updateOne( {
        "$set: { "Profession_id": ObjectId(document.Profession_id) }
    } );
    count++;
    if (count % 1000 === 0) {
        // Execute per 1000 operations and re-init
        bulk.execute();
        bulk = db.collection.initializeUnorderedBulkOp();
    }
});

// Clean up queues
if (count > 0)
    bulk.execute();

https://stackoverflow.com/questions/37718005/

相关文章:

mongodb - Mongo在计算条件下排序

ruby-on-rails - 运行 Rails 应用程序时的 Mongo::Error::NoSe

mongodb - Docker-MongoDB 中的身份验证问题

linux - PHP升级到7后,为什么不能使用mongodb驱动?

java - 使用 Spring Data 按提取的日期、月份和年份聚合项目组

php - 在 Ubuntu 14 上将 PHP Mongo 扩展更新到 1.5

node.js - NodeJS 崩溃 : Mongoose findById() does NOT

mongodb - 按 id 对 Mongo 文档进行分组,并按时间戳获取最新文档

python - 具有完整行对象的 Mongo Distinct Query

javascript - Passport 没有保持持久的登录 session