mongodb: 全局替换所有对一个 ObjectID 的引用?
mongodb: Globally replace all references to one ObjectID with another?
所以我有一个 MongoDB 数据库,在几个集合中有数百万条记录。这是一些记录的(大大简化的)示例...
集合 A 文件看起来像:
{
_id: ObjectID(....)
name: "Hubert Humphrey"
}
集合 B 文件看起来像:
{
_id: ObjectID(....)
ReferenceSummary: [
{
person: ObjectID(<some-ID-from-Collection-A>)
count: 312
},
{
person: ObjectID(<some-other-ID-from-Collection-A>)
count: 42
},
...
],
TopPeople: [ ObjectID(<another-ID-from-Collection-A>), ObjectID(<yet-another-ID-from-Collection-A>), ...]
}
问题来了。我们意识到我们在 Collection A 中有一些重复项(只有 3 或 4 个)。它们在 Collection B 中都被引用了数十万次。
但是,没有出现给定集合 B 文档引用两个不同的集合 A 文档的情况,这两个文档彼此重复。
所以,我需要做的是解决这个问题:对于集合 A 中的每一对重复项,使用 _id
的 ObjectId(X)
和 ObjectId(Y)
,替换所有出现的ObjectId(Y)
和 ObjectId(X)
用于集合 B 中的所有文档。
如果我处理的是原始 JSON 文件,我只需进行字符串替换即可。
在 mongo shell 中是否有一种简单的方法可以做到这一点,只需对每个集合 A 的副本使用一个命令?
完成这项工作最简单的方法是使用forEach
循环
var ids = [id1, id2, ...., idN];
var idsToReplace = [id1TR, id2TR, ...., IdNTR];
var aLenght = ids.lenght;
for (var i = o; i < aLenght; i++) {
db.collectionA.find({
_id : ids[i]
}).forEach(function (doc) {
doc.fieldA = idsToReplace[i];
// if we habve an array entry we need to iterate thru it
var arrayXLenght = doc.arrayX.lenght;
for (var j = 0; j < arrayXLenght; j++) {
if (doc.arrayX[j].field === ids[i]) {
doc.arrayX[j].field = idsToReplace[i];
}
}
prinjson(doc); //verify changes
//doc.save() //uncoment when you wil be assured that changes are ok
})
// same thing with other collection
}
所以我有一个 MongoDB 数据库,在几个集合中有数百万条记录。这是一些记录的(大大简化的)示例...
集合 A 文件看起来像:
{
_id: ObjectID(....)
name: "Hubert Humphrey"
}
集合 B 文件看起来像:
{
_id: ObjectID(....)
ReferenceSummary: [
{
person: ObjectID(<some-ID-from-Collection-A>)
count: 312
},
{
person: ObjectID(<some-other-ID-from-Collection-A>)
count: 42
},
...
],
TopPeople: [ ObjectID(<another-ID-from-Collection-A>), ObjectID(<yet-another-ID-from-Collection-A>), ...]
}
问题来了。我们意识到我们在 Collection A 中有一些重复项(只有 3 或 4 个)。它们在 Collection B 中都被引用了数十万次。
但是,没有出现给定集合 B 文档引用两个不同的集合 A 文档的情况,这两个文档彼此重复。
所以,我需要做的是解决这个问题:对于集合 A 中的每一对重复项,使用 _id
的 ObjectId(X)
和 ObjectId(Y)
,替换所有出现的ObjectId(Y)
和 ObjectId(X)
用于集合 B 中的所有文档。
如果我处理的是原始 JSON 文件,我只需进行字符串替换即可。
在 mongo shell 中是否有一种简单的方法可以做到这一点,只需对每个集合 A 的副本使用一个命令?
完成这项工作最简单的方法是使用forEach
循环
var ids = [id1, id2, ...., idN];
var idsToReplace = [id1TR, id2TR, ...., IdNTR];
var aLenght = ids.lenght;
for (var i = o; i < aLenght; i++) {
db.collectionA.find({
_id : ids[i]
}).forEach(function (doc) {
doc.fieldA = idsToReplace[i];
// if we habve an array entry we need to iterate thru it
var arrayXLenght = doc.arrayX.lenght;
for (var j = 0; j < arrayXLenght; j++) {
if (doc.arrayX[j].field === ids[i]) {
doc.arrayX[j].field = idsToReplace[i];
}
}
prinjson(doc); //verify changes
//doc.save() //uncoment when you wil be assured that changes are ok
})
// same thing with other collection
}