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

Javascript 如何更新mongodb文档字符串的一部分?,javascript,mongodb,Javascript,Mongodb,我的收藏如下: { "_id": 1, "integration_id": 222, "log_file": "/var/www/html/logs/posts/10608.log", "active": true, }, { "_id": 2, "integration_id": 344

我的收藏如下:

  {
    "_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\u文件的所有文档,但我只想更新日志文件的路径。例如
/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);
})
但什么也没发生。没有错误或任何类型的输出,也没有更新任何内容。有人能帮忙吗


无论如何,我使用的是MongoDB Atlas。只是想说出来,以防有人知道他们对这类操作施加的任何限制。

我会使用
$exists
,您还需要将
日志文件
设置为
替换的结果(
替换
未替换到位):


我将使用
$exists
,您还需要将
日志文件
设置为
替换
的结果(
替换
未就地替换):


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

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

如果要使用MongoDB聚合。你可以这样做

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