title: Getting first occurrence in last sequence with data
body: <p>I need to to get the first occurrence in the last sequence of data inserted to database. It would be great if it could be done in one query.</p>
  
  <p>Let's say I have data like this: </p>
  
  <pre><code>{_id:......,ts:Date("2017-10-24T00:00:00.000Z"), id: 1, ok: false}
  {_id:......,ts:Date("2017-10-23T00:00:00.000Z"), id: 1, ok: false}
  {_id:......,ts:Date("2017-10-22T00:00:00.000Z"), id: 1, ok: true}
  {_id:......,ts:Date("2017-10-21T00:00:00.000Z"), id: 1, ok: true}
  {_id:......,ts:Date("2017-10-20T00:00:00.000Z"), id: 1, ok: false}
  {_id:......,ts:Date("2017-10-21T00:00:00.000Z"), id: 2, ok: false}
  {_id:......,ts:Date("2017-10-20T00:00:00.000Z"), id: 2, ok: true}
  </code></pre>
  
  <p>and I need to get for every ID the first occurrence when the field ok was false in the last sequence when the ok is false. </p>
  
  <pre><code>{_id:......,ts:Date("2017-10-23T00:00:00.000Z"), id: 1, ok: false}
  </code></pre>
  
  <p>but I need it for every id. It seems impossible for me to do it scalable so I won't need x thousand of queries to the database. I know how to make it for one ID but if I would need to send query for every ID the database would be overwhelmed.</p>
  
  <p>This is my current query:</p>
  
  <pre><code>{
      $sort : {ts : -1}
  },
  {
      $match : {"ok" : true }
  },
  {
      $group : {
          _id : {id : "$id"},
          last : {$last : "$$CURRENT"}
      }
  }
  </code></pre>
  
  <p>This gives me for every id the last data with ok true.</p>
  
  <p>But I need the data after it. Is there any simple scalable way how to do it for the ok false ??</p>
  
  <p>I tried to use foreach function on aggregate but if I do that I get error </p>
  
  <blockquote>
    <p>TypeError: db.getCollection(...).aggregate(...).foreach is not a function</p>
  </blockquote>
  
  <p>So I don't know then ... is it even possible to do that? </p>