Search code examples
couchbasesql++

How do I select and update just the name values from this map in Couchbase?


I have a set of documents of the type:

contactId: V123132,
{
    "accessMap": {
      "136400": [
        "STANDARD"
      ],
      "136401": [
        "STANDARD"
      ],
      "136535": [
        "STANDARD"
      ],
      "136672": [
        "RG0763",
        "ADMIN",
        "STANDARD"
      ],
      "136676": [
        "RG0763",
        "ADMIN",
        "STANDARD"
      ]
    }
  },
"documentType": "ACS_MAP"

I want to update the keys of the accessMap and append a ":2" at the end of each key in the accessMap,I'm trying to figure out how to write query for that.

What I've done so far is to select the keys of the accessMap I did a:

SELECT OBJECT_NAMES(contact-services.accessMap) from contact-services where documentType = "ACS_MAP"

which gives me:

{
    "$1": [
      "136400",
      "136401",
      "136535",
      "136672",
      "136676"
    ]
}

I'm not sure if this is the right approach for it..?


Solution

  • To change values you need to use UPDATE statement. UPDATE statement LHS of SET/UNSET needs path, so you need to aware of the path you want to update. You have ARRAY you can use any ARRAY functions https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/arrayfun.html or construct new ARRAY

    UPDATE default AS d
    SET d.accessMap.`136672` = ARRAY_APPENED(d.accessMap.`136672`,"xyz")
    WHERE ......;
    
    UPDATE default AS d  
    SET d.accessMap.[v] = ARRAY_APPEND(d.accessMap.[v], "hello") 
                   FOR v IN OBJECT_NAMES(d.accessMap) 
                   WHEN v IN ["136672", "136676"] END 
    WHERE ....;
    

    post fix ":2" every key of accessMap. If need specific pattern use CASE expression.

    UPDATE default AS d  
    SET d.accessMap = OBJECT (v.name|| ":2") : v.val FOR v IN OBJECT_PAIRS(d.accessMap) END 
    WHERE ....;