简体   繁体   English

如何更新 mongodb 文档字符串的一部分?

[英]How to update part of a string of mongodb documents?

My collection looks like this:我的收藏看起来像这样:

  {
    "_id": 1,
    "integration_id": 222,
    "log_file": "/var/www/html/logs/posts/10608.log",
    "active": true,
    
  },
  {
    "_id": 2,
    "integration_id": 344,
    "log_file": "/var/www/html/logs/posts/10223.log",
    "active": true,
    
  },
  {
    "_id": 3,
    "integration_id": 124,
    "log_file": "/var/www/html/logs/posts/19178.log",
    "active": true,
    
  },
  {
    "_id": 4,
    "integration_id": 872,
    "active": true,
    
  }

I want to update all documents where log_file is present, but I want to update only the path to the log file.我想更新log_file存在的所有文档,但我只想更新日志文件的路径。 For example /var/www/html/logs/posts/10608.log should become /new/path/to/log/10608.log例如/var/www/html/logs/posts/10608.log应该变成/new/path/to/log/10608.log

The end result should be:最终结果应该是:

{
    "_id": 1,
    "integration_id": 222,
    "log_file": "/new/path/to/log/10608.log",
    "active": true,

  },
  {
    "_id": 2,
    "integration_id": 344,
    "log_file": "/new/path/to/log/10223.log",
    "active": true,
  }
...
...

I tried running this command from the shell:我尝试从 shell 运行此命令:

db.collection.find({
    log_file: {
        "$ne": null
    }
}).forEach(function(d, i) {
    d.log_file.replace("/var/www/html/logs/posts/", "/new/path/to/log/");
    db.collection.save(d);
})

But nothing happens.但什么也没有发生。 No errors or any kind of output and nothing is updated.没有错误或任何类型的 output 并且没有任何更新。 Can someone help?有人可以帮忙吗?

For what it's worth, I'm using MongoDB Atlas.对于它的价值,我使用的是 MongoDB Atlas。 Just wanted to put that out there in case someone knows of any limitations on these kinds of operations they impose.只是想把它放在那里,以防有人知道他们对这类操作施加的任何限制。

I would use $exists , also you need to set log_file to the result of the replace ( replace does not replace in place):我会使用$exists ,您还需要将log_file设置为replace的结果( replace不会替换到位):

db.collection.find({
    log_file: {$exists: true}
}).forEach(function(d, i) {
    d.log_file = d.log_file.replace("/var/www/html/logs/posts/", "/new/path/to/log/");
    db.collection.save(d);
})

If you would like to use MongoDB aggregation.如果您想使用 MongoDB 聚合。 You can do something like this.你可以做这样的事情。

    db.collection.aggregate([
      {
        "$addFields": {
          log_file: {
            $replaceOne: {
              input: "$log_file",
              find: "/var/www/html/logs/posts/",
              replacement: "/new/path/to/log/"
            }
          }
        }
      }
    ])

You can check Playground here.你可以在这里查看游乐场。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM