Search code examples
rethinkdbrethinkdb-javascript

Rethinkdb filter on an earlier query


I have a table "posts" with "timestamp".

Now I want from all user that have more than 1 post, to get all posts EXCEPT the most recent post.

With this query I can successfully check the users who have more than 1 post:

r.table("post")
  .group('userId')
  .count()
  .ungroup()
  .filter(r.row("reduction").gt(1))

I can get the last post of a specific user by doing

r.table("post")
.filter({userId: 'xxx'})
.max('timestamp')

Now I need to tie those somehow together, and then compare the timestamp from each row with the max('timestamp') to see if they are not equal. The following is what I had but it's obviously wrong

.filter(r.row('timestamp').ne(r.row('timestamp').max('timestamp')('timestamp')))

Any advice how I bring all this together?


Solution

  • Something like this ought to work:

    r.table('post')
    .group({
        index: 'userId'
    })
    .ungroup()
    .filter(function(doc) { 
        return doc('reduction').count().gt(1)
    })
    .group('group')('reduction')
    .nth(0)
    .orderBy(
        r.desc('timestamp')
    ).skip(1)
    

    With reservations for syntax errors; I built this query using python and then converted it to javascript. Especially unsure about the .nth(0) part, never used it in javascript. In python it's just [0].