Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

Couchbase - SELECT a subset of fields from array of objects

I am using the travel-sample data set, and am running the following query:

SELECT id, schedule FROM `travel-sample`WHERE type = "route" LIMIT 1;

It is returning with the following results:

[
  {
    "id": 10000,
    "schedule": [
      {
        "day": 0,
        "flight": "AF198",
        "utc": "10:13:00"
      },
      {
        "day": 0,
        "flight": "AF547",
        "utc": "19:14:00"
      },
      ...
    ]
  }
]

However, I don't want to return the schedule.$.day field; i.e. I want my results to be:

[
  {
    "id": 10000,
    "schedule": [
      {
        "flight": "AF198",
        "utc": "10:13:00"
      },
      {
        "flight": "AF547",
        "utc": "19:14:00"
      },
      ...
    ]
  }
]

How can I SELECT only a subset of object fields from an array of objects?


I have tried UNNEST but I don't want to have a separate record for each schedule element - I want the schedule elements to remain nested inside the document.

I have also tried using OBJECT_REMOVE

SELECT id, ARRAY OBJECT_REMOVE(x, 'day') FOR x in schedule END AS schedule FROM `travel-sample` WHERE type = "route" LIMIT 1;

But I want to whitelist rather than blacklist fields.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your last attempt was close. Instead of using OBJECT_REMOVE, you can simply construct the object you want returned.

SELECT id, ARRAY {"flight": x.flight, "utc": x.utc} FOR x in schedule END AS schedule FROM `travel-sample` WHERE type = "route" LIMIT 1;

You will get the following results:

[
  {
    "id": 10000,
    "schedule": [
      {
        "flight": "AF198",
        "utc": "10:13:00"
      },
      {
        "flight": "AF547",
        "utc": "19:14:00"
      },
      ...
    ]
  }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...