使用Update Query

时间:2016-06-09 06:04:57

标签: 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"
}

请帮助我更新MongoDB中的值。

3 个答案:

答案 0 :(得分:5)

我们需要迭代文档的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();

答案 1 :(得分:0)

我在mongo 4.0中使用了以下代码

var requests = [];    
let cursor = db.collection.find({}, { "to": 1 });
cursor.forEach( document => { 
    requests.push( { 
        "updateOne": {
            "filter": { "_id": document._id },
            "update": { "$set": { "to": ObjectId(document.to) } }
        }
    });
    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);

答案 2 :(得分:0)

您可以这样做:

db.collectionName.find({
    id: {
        $type: 2
    }
}).forEach (doc => {
    db.stringToObject.update({
        _id: doc._id
    }, {
        "$set": {
            "Profession_id": ObjectId(doc.Profession_id) 
        } 
    })
})