1

Let's suppose I have a collection named "repos" containing objects like this one:

{
  name: 'myrepo',
  actions: [
     { timestamp: '2016-04-12T14:43:20Z', change: 'add' },
     { timestamp: '2016-04-12T14:45:10Z', change: 'remove' },
     { timestamp: '2016-04-12T15:03:03Z', change: 'add' },
     ... and so on ....
  ]
}

Now I want a query to convert each of these objects into something like this:

{
   name: 'myrepo',
   timestamps: ['2016-04-12T14:43:20Z', '2016-04-12T14:45:10Z', '2016-04-12T15:03:03Z'],
   changes: ['add', 'remove', 'add']
}

I have thought of something like the following:

FOR r in repos
LET changes= (FOR a IN r.actions RETURN a.change )
LET timestamps = (FOR a IN r.actions RETURN a.timestamp)
RETURN {
    name: r.name,
    changes: changes,
    timestamps: timestamps
    }

but I am afraid that the double FOR may be not very efficient.

Any suggestion?

1 Answer 1

2

You can express your query in a more compact form using the array expansion operator:

FOR r IN repos RETURN {
  name: r.name,
  changes: r.actions[*].change,
  timestamps: r.actions[*].timestamp
}

You may also use UNIQUE to only get every change type once per record in your result (if the arrays changes and timestamps don't have to lineup):

FOR r IN repos RETURN {
    name: r.name,
    changes: UNIQUE(r.actions[*].change),
    timestamps: r.actions[*].timestamp
}

In general, your query only adds the overhead of two sub-queries, and shouldn't be that much slower than the above. However, it's more compact and therefore a little bit better to read, isn't it?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.