How can I rename field of document with N1QL?

Hello,

I’ve got:

{
   "id": "12345",
   "docType": "Car" 
}

I need to rename “id” field to “carId” and get this:

{
   "carId": "12345",
   "docType": "Car"  
}

What n1ql query can do that?

Thanks for any help

Hi, you can do

UPDATE mybucket
SET carId = id
UNSET id
;

You can also add a WHERE clause if needed.

1 Like

Hi, could you describe how to execute this statement from an SDK?
Thanks,
det

Check this out UNSET from .netClient

I added where type = “example” after unset and it deleted all of id without replacing it with cardId. I double checked spelling.

Please post as separate post with all the details and query and index.

how can we rename a subfield… this is not working for renaming a subfield… thanks in advance!

I know it’s been a while, instead of using SQL++ (N1QL) there is another option.

If you have performance issues or need to process a very large data set the Eventing service works great for renaming both top-level-fields or subfields.

Below I show a “point tool” written to take care of the original rename request.

function OnUpdate(doc, meta) {
    // test if old field exists
    if (doc.id) {
        // modify the local copy of the JSON doc sourced via the DCP stream
        doc.carId = doc.id;
        delete doc.id;
        // update the entire document via a bucket binding to the source in read/write mode.
        binding_to_source[meta.id] = doc;
    }
}

The above function needs to listen to your source bucket (or keyspace if 7.0+) and have a bucket binding alias of binding_to_source to your source bucket (or keyspace if 7.0+) in mode read+write.

For performance you can also increase the # workers in your Eventing function to the number of vCPUs on your Eventing node. I did millions of documents quite fast using this technique.

For more details on using Eventing refer to Examples: Using the Eventing Service | Couchbase Docs

Best

Jon Strabala
Principal Product Manager - Server‌