n1ql query to update multiple parameters in array of json data

一曲冷凌霜 提交于 2019-11-29 23:20:32

问题


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"
  }
]}

回答1:


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;


来源:https://stackoverflow.com/questions/37152577/n1ql-query-to-update-multiple-parameters-in-array-of-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!