n1ql查询更新json数据数组中的多个参数

时间:2016-05-11 03:22:32

标签: json couchbase n1ql

以下是couchbase中的示例文档(userdetails)。

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

基于"公司",我想更改"名字"和"姓氏"

N1ql查询(更新单个参数(名字))

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

以上查询效果很好。
但我在写查询更新两个参数(名字,姓氏)

时苦苦挣扎

N1ql查询(更新两个参数)

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

以上查询,仅更新"姓氏"。

输出

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

1 个答案:

答案 0 :(得分:2)

每个SET术语都是独立的,因此您可以执行以下操作:

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;

要回答您的评论,以下两种形式可避免双循环。您可以使用实际数据进行测量,以查看哪种形式可以提供最佳性能。

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;