使用Update Query将文档值从字符串更改为ObjectId

6 mongodb mongodb-query

我需要为mongodb集合中的所有文档更新Profession_id字符串ObjectId的值.

我的收藏专业是(这里我只粘贴了2份文件,实际上我的文件超过10K)

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

{
    "_id" : ObjectId("575845d213d284da0ac2ee82"),
    "Profession_id" : "575841b313d284da0ac2ee7d",
    "Prof_Name" : "Executive Officer"
}
Run Code Online (Sandbox Code Playgroud)

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

sty*_*ane 5

我们需要迭代snapshot()我们的文档并使用$setupdate运算符更新每个文档.为此,我们使用批量操作以实现最高效率.

从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);     
Run Code Online (Sandbox Code Playgroud)

从MongoDB 2.6到3.0,您需要使用现已弃用的BulkAPI及其关联方法.

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();
Run Code Online (Sandbox Code Playgroud)