Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couchbase N1QL: Update on nested Documents

When having a nested document like this:

{
"blog": "testblog1",
"user_id": 41,
"comments": [
    {
        "comment": "testcomment1",
        "user_id": 883
    },
    {
        "comment": "testcomment2",
        "user_id": 790
    }
  ]
}

can one do an Update Operation with N1QL to add an extra field to a subdocument?

I would like to add the field "ranking" : "top comment" to the subdocument with the comment testcomment2:

{
"blog": "testblog1",
"user_id": 41,
"comments": [
    {
        "comment": "testcomment1",
        "user_id": 883
    },
    {
        "comment": "testcomment2",
        "user_id": 790,
        "ranking" : "top comment"
    }
  ]
}

Site Note: The following statement would add a field to the root document on the Collection Blog:

UPDATE Blog SET rank = "top blog" WHERE blog = "testblog1";
like image 331
gehtmaguad Avatar asked Dec 19 '22 05:12

gehtmaguad


1 Answers

Yes, you can do the following in N1QL:

UPDATE Blog
SET c.ranking = "top comment" FOR c IN comments WHEN c.comment = "testcomment2" END
WHERE blog = "testblog1"

like image 193
geraldss Avatar answered Jan 04 '23 16:01

geraldss