英文:
Replace any value matching a specific value in MongoDb
问题
我想在任何嵌套文档的任何级别中替换一个与预定义值相等的值。我该如何实现这一点?我能够循环遍历集合中的所有文档和文档中的所有属性,但不知道如何处理嵌套级别。
我现在拥有的:
function Replace() {
var replacement = { oldValue: "abc", newValue: "def" }
db.MyCollection.find().forEach((it)=> {
for (var prop in it) {
if (it.hasOwnProperty(prop)) {
console.log("Property:", prop);
console.log("Value:", it[prop]);
// 比较和替换
// 只处理第一层级。我如何处理所有嵌套层级?
}
}
})
}
Replace();
英文:
I would like to replace a value in any level of nested document where it is equal to a predefined value. How can I achieve that? I am able to loop through all document in the collection and all properties in the document but do not know how to handle nested levels
What I have right now
function Replace() {
var replacement = { oldValue: "abc", newValue: "def" }
db.MyCollection.find().forEach((it)=> {
for (var prop in it) {
if (it.hasOwnProperty(prop)) {
console.log("Property:", prop);
console.log("Value:", it[prop]);
// Comparison and replacement
// Only hande the first level. How can I handle all nested level?
}
}
})
}
Replace();
答案1
得分: 1
你可以编写一个JavaScript代码片段并在mongosh
中执行它。类似这样:
db = connect('mongodb://localhost/database-name');
const replacement = { oldValue: "abc", newValue: "def" }
const docs = db.collectionName.find({}).toArray();
for (let j = 0; j < docs.length; j++) {
updateValue(docs[j])
db[collections[i]].replaceOne({ _id: docs[j]._id }, docs[j]);
}
function updateValue(doc) {
Object.keys(doc).forEach(key => {
if (doc[key] === replacement.oldValue) {
doc[key] = replacement.newValue;
} else if (doc[key] instanceof Object && !Array.isArray(doc[key])) {
updateValue(doc[key])
} else if (Array.isArray(doc[key])) {
doc[key].forEach(val => {
updateValue(val)
})
}
})
}
英文:
You can write a javascript code snippet and execute it on the mongosh
itself. Something like this:
db = connect('mongodb://localhost/database-name');
const replacement = { oldValue: "abc", newValue: "def" }
const docs = db.collectionName.find({}).toArray();
for (let j = 0; j < docs.length; j++) {
updateValue(docs[j])
db[collections[i]].replaceOne({ _id: docs[j]._id }, docs[j]);
}
function updateValue(doc) {
Object.keys(doc).forEach(key => {
if (doc[key] === replacement.oldValue) {
doc[key] = replacement.newValue;
} else if (doc[key] instanceof Object && !Array.isArray(doc[key])) {
updateValue(doc[key])
} else if (Array.isArray(doc[key])) {
doc[key].forEach(val => {
updateValue(val)
})
}
})
}
This snippet will update one document at a time. Please note that since it is based on recursion, the script might fail if you have around too many nested levels.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论