繁体   English   中英

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

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

我的收藏看起来像这样:

  {
    "_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,
    
  }

我想更新log_file存在的所有文档,但我只想更新日志文件的路径。 例如/var/www/html/logs/posts/10608.log应该变成/new/path/to/log/10608.log

最终结果应该是:

{
    "_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,
  }
...
...

我尝试从 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);
})

但什么也没有发生。 没有错误或任何类型的 output 并且没有任何更新。 有人可以帮忙吗?

对于它的价值,我使用的是 MongoDB Atlas。 只是想把它放在那里,以防有人知道他们对这类操作施加的任何限制。

我会使用$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);
})

如果您想使用 MongoDB 聚合。 你可以做这样的事情。

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

你可以在这里查看游乐场。

暂无
暂无

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

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