Search code examples
jsoncouchbasesql++

n1ql query to update multiple parameters in array of json data


Following is the sample document ( userdetails) in couchbase.

{
"friends": [
  {
    "company": "microsoft",
    "firstname": "criss",
    "lastname": "angel"
  },
  {
    "company": "google",
    "firstname": "captain",
    "lastname": "america"
  }
]}

based on the "company", i want to change the "firstname" and "lastname"

N1ql query ( to update single parameter (firstname) )

update default use keys "userdetails" set a.firstname="xyz" for a in friends when a.company="microsoft" end returning friends

Above query works perfectly.
but Im struggling in writting query for updating two parameters ( firstname,lastname)

N1ql query ( to update two parameter)

update default use keys "userdetails" set a.firstname="abc",a.lastname="xyz" for a in friends when a.company="microsoft" end returning friends

Above query, is updating only "lastname".

output

{
"friends": [
  {
    "company": "microsoft",
    "firstname": "criss",
    "lastname": "xyz"
  },
  {
    "company": "google",
    "firstname": "captain",
    "lastname": "america"
  }
]}

Solution

  • Each SET term is independent, so you can do the following:

    UPDATE default
    USE KEYS "userdetails"
    SET a.firstname="abc" FOR a IN friends WHEN a.company="microsoft" END,
        a.lastname="xyz" FOR a IN friends WHEN a.company="microsoft" END
    RETURNING friends;
    

    To answer your comment, the following two forms avoid the double loop. You can measure with actual data to see which form gives the best performance.

    UPDATE default
    USE KEYS "userdetails"
    SET friends[i] = {"firstname":"abc", "lastname":"xyz", "company":"microsoft"} FOR i : a IN friends WHEN a.company="microsoft" END
    RETURNING friends;
    
    UPDATE default
    USE KEYS "userdetails"
    SET friends[i] = OBJECT_PUT(OBJECT_PUT(a, "firstname", "abc"), "lastname", "xyz") FOR i : a IN friends WHEN a.company="microsoft" END
    RETURNING friends;