title: MongoDB: Group and then subtract
body: <p>I have a list of books. I would like to get the authors who have been writting books for a longer period. I wanted to do that substracting the year of their last book, and the year of their first one.
  My database looks like this:</p>
  <pre><code>{&quot;_id&quot;: ObjectID(&quot;1), &quot;title&quot;: &quot;Harry Potter&quot;, &quot;year&quot;: NumberInt(2000), &quot;author&quot;: &quot;JK. Rowling&quot;}, 
  &quot;_id&quot;: ObjectID(&quot;1), &quot;title&quot;: &quot;Harry Potter 99&quot;, &quot;year&quot;: NumberInt(2020), &quot;author&quot;: &quot;JK. Rowling&quot;}
  </code></pre>
  <p>So, my code so far looks like this:</p>
  <pre><code>phase1= {$group:{&quot;_id&quot; : &quot;$author&quot;}, &quot;enddate&quot; : {$max: &quot;$year&quot;}, &quot;startdate&quot;: {$min: &quot;$year&quot;}}    
  
  phase2 = {&quot;total&quot; : {$subtract : [&quot;$enddate&quot;, &quot;$startdate&quot;]}
  steps = [phase1, phase2]
  
  db.actors.aggregate(steps)
  </code></pre>
  <p>This is not working for me, so I would like if someone could help me to write a correct code to do this. The result should look like this:</p>
  <pre><code>{
  
  &quot;_id&quot; : &quot;JK. Rowling&quot;,
  
  &quot;startdate&quot; : 2000,
  
  &quot;enddate&quot; : 2020,
  
  &quot;total&quot; : 20
  
  }
  </code></pre>
  <p>Thanks.</p>