gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:37:54 26 4
gpt4 key购买 nike

我需要将 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();

关于mongodb - 使用更新查询将文档值从字符串更改为 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com