3

I have one collection for users, one for user's calendars, (users:calendars have 1:1 relation, but not all user owns a calendar):

users: {"name":"John","role":admin [more fields]}
calendars: {"color":"blue",owner: "users/john"}

I've to return a document with:

{"name":"John","role":admin,[all fields from the users collection],calendar:cal}

Is there a way to do this without listing the properties from the user document?

for cal in zcalendar
    for user in zuser filter user._id == cal.owner
return ...
yojimbo87
  • 65,684
  • 25
  • 123
  • 131
legikaloz
  • 35
  • 4

1 Answers1

2

You can use MERGE document function, e.g. like this:

FOR cal IN zcalendar
    FOR user IN zuser
        FILTER user._id == cal.owner
        LET calDoc = {
            'calendar': cal
        }
        RETURN MERGE(user, calDoc)

Which returns this structure:

[
  {
    "_id": "...",
    "_rev": "...",
    "_key": "...",
    "name": "John",
    "role": "admin",
    "calendar": {
      "_id": "...",
      "_rev": "...",
      "_key": "...",
      "color": "blue",
      "owner": "..."
    }
  }
]
yojimbo87
  • 65,684
  • 25
  • 123
  • 131
  • I'd like to return calDoc as a sub document but with `MERGE` it is not possible. – legikaloz Dec 01 '14 at 10:41
  • @legikaloz calDoc in the example is returned as embedded calendar field within user document which seems to be what you posted in your question. Can you provide exact query which you are using and where MERGE doesn't work as expected? – yojimbo87 Dec 01 '14 at 10:59
  • Sorry, I overlooked the `LET` expression, which embeds the found cal document. Your answer is good, should be accepted. – legikaloz Dec 01 '14 at 11:07