[英]Change MongoDb _id from string to ObjectId
We have documents that were originally stored using the StringObjectIdGenerator type for _id.我们有最初使用 _id 的 StringObjectIdGenerator 类型存储的文档。 Newer data will be saved using the default ObjectIdGenerator.
较新的数据将使用默认的 ObjectIdGenerator 保存。 We would like to be able to migrate the existing data by converting the _id to the new data type.
我们希望能够通过将 _id 转换为新数据类型来迁移现有数据。 Is this possible?
这可能吗?
Yes, it's possible to change data type, we need to find all documents with string id, using the iterator we can clone a document by changing its _id, after cloning we just need to delete the old document.是的,可以更改数据类型,我们需要找到所有带有字符串 id 的文档,使用迭代器我们可以通过更改文档的 _id 来克隆文档,克隆后我们只需要删除旧文档。
Below is for a small document, for large collection you may need to use db.collection.initializeUnorderedBulkOp()
for bulk insert/delete下面是一个小文档,对于大集合,您可能需要使用
db.collection.initializeUnorderedBulkOp()
进行批量插入/删除
db.i.find({_id : {$type : 2}}). //find all string _id
forEach(function(d){
var id = ObjectId(d._id); //_id to ObjectId
var oldId = d._id; // _id
d._id = id;
db.i.insert(d); // clone doc with new Id
db.i.remove({ _id : oldId }); // delete old doc
}
)
Example例子
> db.i.insertMany([{},{},{},{_id : "4a5ec389fee4c182f509f3ba"}, {_id : "4b5ec389fee4c182f509f3ba"}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5a5ec9edfee4c182f509f3c9"),
ObjectId("5a5ec9edfee4c182f509f3ca"),
ObjectId("5a5ec9edfee4c182f509f3cb"),
"4a5ec389fee4c182f509f3ba",
"4b5ec389fee4c182f509f3ba"
]
}
> db.i.find()
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3c9") }
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3ca") }
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3cb") }
{ "_id" : "4a5ec389fee4c182f509f3ba" }
{ "_id" : "4b5ec389fee4c182f509f3ba" }
> db.i.find({_id : {$type : 2}}).
... forEach(function(d){
... var id = ObjectId(d._id);
... var oldId = d._id;
... d._id = id;
... db.i.insert(d);
... db.i.remove({ _id : oldId });
... }
... )
> db.i.find()
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3c9") }
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3ca") }
{ "_id" : ObjectId("5a5ec9edfee4c182f509f3cb") }
{ "_id" : ObjectId("4a5ec389fee4c182f509f3ba") }
{ "_id" : ObjectId("4b5ec389fee4c182f509f3ba") }
>
db.inventries.find({ _id: { $type: 2 } }).forEach(function (d) { var id = ObjectId(d._id); var oldId = d._id; d._id = id; db.inventries.insert(d); db.inventries.remove({ _id: oldId }); } )
// change inventries => your collection name
hit above commend in mongodb console在 mongodb 控制台中点击上述推荐
db.getCollection('Files').find({"_id":{"$exists":true}}).forEach(function(x){
let id;
try {
id = new ObjectId(x._id);
}
catch (err) {
id = new ObjectId();
}
db.Files.update( { "_id": x._id}, { $set: { _id:id } } );
}
) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.