在MongoDb中替换匹配特定值的任何数值。

huangapple go评论45阅读模式
英文:

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(&#39;mongodb://localhost/database-name&#39;);
const replacement = { oldValue: &quot;abc&quot;, newValue: &quot;def&quot; }
const docs = db.collectionName.find({}).toArray();
for (let j = 0; j &lt; docs.length; j++) {
     updateValue(docs[j])
     db[collections[i]].replaceOne({ _id: docs[j]._id }, docs[j]);
}
​
function updateValue(doc) {
    Object.keys(doc).forEach(key =&gt; {
        if (doc[key] === replacement.oldValue) {
            doc[key] = replacement.newValue;
        } else if (doc[key] instanceof Object &amp;&amp; !Array.isArray(doc[key])) {
            updateValue(doc[key])
        } else if (Array.isArray(doc[key])) {
            doc[key].forEach(val =&gt; {
                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.

huangapple
  • 本文由 发表于 2023年5月22日 11:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定