通过替换值更新多个字段值MongoDB

时间:2018-06-14 16:13:10

标签: mongodb

我希望在MongoDB中更新我的对象,如下所示

{ 
    "_id" : BinData(0, "vcbcbcbcvbdfsdgbbdvZNImOMQM6g=="), 
    "mypath" : "/sample/old/path/content/a/b", 
    "report_suite" : "mongo", 
    "target_s" : "/sample/old/path/content/c/d", 
    "topic_s" : "feed", 
    "id" : "/sample/old/path/content/retrieved/d4076995-f8a7-4b9f-912b-6f251a2fddcb", 
    "timestamp" : NumberLong(1527875028199)
}

{ 
    "_id" : BinData(0, "vcbcbcbcvbdfsdgbbdvZNImOMQM6g=="), 
    "mypath" : "/sample/new/path/content/a/b", 
    "report_suite" : "mongo", 
    "target_s" : "/sample/new/path/content/c/d", 
    "topic_s" : "feed", 
    "id" : "/sample/new/path/content/retrieved/d4076995-f8a7-4b9f-912b-6f251a2fddcb", 
    "timestamp" : NumberLong(1527875028199)
}

基本上所有具有路径/样本/旧/路径/内容到样本/新/路径/内容的字段值

请帮忙。

我试过了

db.content.updateOne(
   { id:"/sample/old/path/content/retrieved/d4076995-f8a7-4b9f-912b-6f251a2fddcb" },
   {
     $set: { "target_s": "/sample/new/path/content/c/d" }
   }
)

但是,我不想将“/ sample / new / path / content / c / d”作为值,而只是将“/ sample / old / path / content”替换为“/ sample / new / path /”内容“和其他剩余部分相同

1 个答案:

答案 0 :(得分:0)

您只需指定要更新的$set中的所有字段:

db.content.updateOne(
   { id:"/sample/old/path/content/retrieved/d4076995-f8a7-4b9f-912b-6f251a2fddcb" },
   {
     $set: {
        "mypath": "new path",
        "target_s": "new path",
        "id": "new path",
      }
   }
)