title: How to replace all the values with the same key in a JSON tree
body: <p>Before storing any JSON document in MongoDB, I need to transform all the string <code>id</code>s in the document into BSON <code>id</code>s and, vice-versa, when reading any document from MongoDB, I need to transform all the BSON <code>id</code>s into string <code>id</code>. That said, given the following JSON...</p>
  
  <pre><code>{
    "id" : "52fe942b790000790079b7d0",
    "email" : "joe@domain.com",
    "username" : "joe",
    "subscriptions" : [
      {
        "accountId" : "72fe942b790000790079b755",
        "name" : "test 1",
        "isDefault" : true
      },
      {
        "accountId" : "72fe942b796850790079b743",
        "name" : "test 2",
        "isDefault" : false
      }
    ]
  }
  </code></pre>
  
  <p>... I need to transform it as described here below before storing it in MongoDB...</p>
  
  <pre><code>{
    "_id" : {"$oid" : "52fe942b790000790079b7d0"},
    "email" : "joe@domain.com",
    "username" : "joe",
    "subscriptions" : [
      {
        "accountId" : {"$oid" : "72fe942b790000790079b755"},
        "name" : "test 1",
        "isDefault" : true
      },
      {
        "accountId" : {"$oid" : "72fe942b796850790079b743"},
        "name" : "test 2",
        "isDefault" : false
      }
    ]
  }
  </code></pre>
  
  <p>... and of course I need to convert back all the BSON <code>id</code>s into string <code>id</code>s when reading the document from MongoDB.</p>
  
  <p>Here below is the code I've tried to convert BSON <code>id</code>s into string <code>id</code>s (using the <code>JsZipper</code> library):</p>
  
  <pre><code>def toPublic(json: JsValue, key: String) = json.updateAllKeyNodes {
    case ((__ \ key), value) =&gt; (key -&gt; value \ "$oid")
  }
  </code></pre>
  
  <p>Given that this method does not transform <code>id</code> into <code>_id</code>, it doesn't work at all and always  returns <code>res0: play.api.libs.json.JsValue = {"accounts":null}</code>; on the other hand, if I hardcode the key like this...</p>
  
  <pre><code>def toPublic(json: JsValue) = json.updateAllKeyNodes {
    case ((__ \ "accountId"), value) =&gt; ("accountId" -&gt; value \ "$oid")
  }
  </code></pre>
  
  <p>... it works as expected and I get back the JSON in the second example. I'm a bit lost, so any help would be really appreciated.</p>