title: Complex Mongo query in Python
body: <p>I have a collection named <code>measurements</code>. In this collection, there are only three fields: <code>id</code> (univoque), <code>tmstamp</code> (univoque) and <code>value</code>. Each row which contains a value greater than 0 is considered an alert. All the alerts that occur from the zero state to the next zero state is considered an episode. I want to query the data in such way that it returns it in episodes format. That is to say, each row is an episode.</p>
  
  <p>In order to make it easier to understand, I'll put an example:</p>
  
  <pre><code>{"id":1, tmstamp:1577644027, value:0}
  {"id":2, tmstamp:1577644028, value:0}
  {"id":3, tmstamp:1577644029, value:1}
  {"id":4, tmstamp:1577644030, value:1}
  {"id":5, tmstamp:1577644031, value:2}
  {"id":6, tmstamp:1577644032, value:2}
  {"id":7, tmstamp:1577644033, value:3}
  {"id":8, tmstamp:1577644034, value:2}
  {"id":9, tmstamp:1577644035, value:1}
  {"id":10, tmstamp:1577644036, value:0}
  {"id":11, tmstamp:1577644037, value:1}
  {"id":12, tmstamp:1577644038, value:1}
  {"id":13, tmstamp:1577644039, value:1}
  {"id":14, tmstamp:1577644040, value:0}
  </code></pre>
  
  <p>Given this data, the episodes would be:</p>
  
  <p><code>episode1</code>:</p>
  
  <pre><code>{"id":3, tmstamp:1577644029, value:1}
  {"id":4, tmstamp:1577644030, value:1}
  {"id":5, tmstamp:1577644031, value:2}
  {"id":6, tmstamp:1577644032, value:2}
  {"id":7, tmstamp:1577644033, value:3}
  {"id":8, tmstamp:1577644034, value:2}
  {"id":9, tmstamp:1577644035, value:1}
  </code></pre>
  
  <p><code>episode2</code>:</p>
  
  <pre><code>{"id":11, tmstamp:1577644037, value:1}
  {"id":12, tmstamp:1577644038, value:1}
  {"id":13, tmstamp:1577644039, value:1}
  </code></pre>
  
  <p>My question is: is there any way to query the data in Mongo in order to obtain the result in this format without having to do these operations after the query itself?</p>