How to replace string in all documents in Mongo

后端 未结 4 1772
长发绾君心
长发绾君心 2020-12-13 14:52

I need to replace a string in certain documents. I have googled this code, but it unfortunately does not change anything. I am not sure about the syntax on the line bellow:<

4条回答
  •  既然无缘
    2020-12-13 15:13

    MongoDB can do string search/replace via mapreduce. Yes, you need to have a very special data structure for it -- you can't have anything in the top keys but you need to store everything under a subdocument under value. Like this:

    {
        "_id" : ObjectId("549dafb0a0d0ca4ed723e37f"),
        "value" : {
                "title" : "Top 'access denied' errors",
                "parent" : "system.admin_reports",
                "p" : "\u0001\u001a%"
        }
    }
    

    Once you have this neatly set up you can do:

    $map = new \MongoCode("function () {
      this.value['p'] = this.value['p'].replace('$from', '$to');
      emit(this._id, this.value);
    }");
    $collection = $this->mongoCollection();
    // This won't be called.
    $reduce = new \MongoCode("function () { }");
    $collection_name = $collection->getName();
    $collection->db->command([
      'mapreduce' => $collection_name,
      'map' => $map,
      'reduce' => $reduce,
      'out' => ['merge' => $collection_name],
      'query' => $query,
      'sort' => ['_id' => 1],
    ]);
    

提交回复
热议问题