title: mongodb: how to get the last N records for a each item in a collection?
body: <p>I am trying to identify the last N record for a group of items that reside in the same collection.</p>
  
  <p>For example:</p>
  
  <p>Collection name is foo</p>
  
  <p>in the collection, there is a object call bar.</p>
  
  <p>Collection foo:</p>
  
  <pre><code>{
  {bar: "apples"
  prices: 10.8,
  create_date: 12345678},
  {bar: "apples"
  prices: 12.8,
  create_date: 12345679},
  {bar: "apples"
  prices: 12.8,
  create_date: 12345680},
  {bar: "oranges"
  prices: 12.8,
  create_date: 12345680},
  {bar: "oranges"
  prices: 15.8,
  create_date: 12345681},
  {bar: "oranges"
  prices: 2.8,
  create_date: 12345682}
  }
  </code></pre>
  
  <p>This gets me the second last record for apples.</p>
  
  <pre><code>db.foo.find({ 
      "bar" : "apples"
  }).sort({ 
      "create_date" : -1.0
  }).skip(1).limit(1);
  </code></pre>
  
  <p>But if i want to return apples and oranges in the same record set and get the second last created_date value of each, how can i do this in on single query?</p>
  
  <p>This is my expected output:</p>
  
  <p>(which is basically returning the second value for apples and oranges:</p>
  
  <pre><code>{
  {bar: "apples"
  prices: 12.8,
  create_date: 12345679},
  {bar: "oranges"
  prices: 15.8,
  create_date: 12345681},
  }
  </code></pre>