Jeno Laszlo
Jeno Laszlo

Reputation: 2301

How to retrieve a subset of fields from array of objects using the Couchbase sub-document API?

I am trying to write a lookup which returns an array from a document and skipping some fields:

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

I would like to get all schedule items but only the flight properties. I want to get something like this:

[
   { 
       "flight: "AF198"
   },
   { 
       "flight: "AF547"
   },
   ...
]

bucket.lookupIn(key).get("schedule.flight") doesn’t work. I tried "schedule[].flight", "schedule.$.flight" It seems I always need to know the index.

I saw that this is possible with N1QL.

Couchbase - SELECT a subset of fields from array of objects

Do you guys know how to do this with the Subdocument API? Sorry if it is a trivial question. I just cannot find an example on

https://developer.couchbase.com/documentation/server/current/sdk/subdocument-operations.html

Upvotes: 4

Views: 348

Answers (1)

Paddy
Paddy

Reputation: 1195

Couchbase Subdocument requires the full path, it does not support expansion. In this case it needs to know the index of the array. There are a few other options:

  1. If every path is known, then you could chain all of the subdocument gets. A total of 16 paths can be got at once: bucket.lookupIn(key).get("schedule[0].flight").get(schedule[1].flight")

  2. Get the parent object and filter on the application side: bucket.lookupIn(key).get("schedule")

  3. As mentioned in the question, use N1QL.

Upvotes: 2

Related Questions