title: MongoDB aggregate - match using lte and fallback to gte
body: <p>I have a MongoDB collection with a structure (simplified) like this:</p>
  
  <pre><code>[
    {
      "name" : "name1",
      "instances" : [ 
        {
          "value" : 1,
          "score" : 2,
          "date" : ISODate("2015-03-04T00:00:00.000Z")
        }, 
        {
          "value" : 2,
          "score" : 5,
          "date" : ISODate("2015-04-01T00:00:00.000Z")
        }, 
        {
          "value" : 2.5,
          "score" : 9,
          "date" : ISODate("2015-03-05T00:00:00.000Z")
        }
      ]
    },
    {
      "name" : "name2",
      "instances" : [ 
        {
          "value" : 6,
          "score" : 3,
          "date" : ISODate("2015-03-05T00:00:00.000Z")
        }, 
        {
          "value" : 1,
          "score" : 6,
          "date" : ISODate("2015-03-04T00:00:00.000Z")
        }, 
        {
          "value" : 3.7,
          "score" : 5.2,
          "date" : ISODate("2015-02-04T00:00:00.000Z")
        }
      ]
    },
    {
      "name" : "name3",
      "instances" : [ 
        {
          "value" : 6,
          "score" : 3,
          "date" : ISODate("2015-03-05T00:00:00.000Z")
        }, 
        {
          "value" : 1,
          "score" : 6,
          "date" : ISODate("2015-03-04T00:00:00.000Z")
        }, 
        {
          "value" : 3.7,
          "score" : 5.2,
          "date" : ISODate("2015-02-04T00:00:00.000Z")
        }
      ]
    }
  ]
  </code></pre>
  
  <p>Currently I have an <code>aggregate</code> query that pulls a single instance from each document by a given date:</p>
  
  <pre><code>db.myCollection.aggregate([
    {$unwind: "$instances"},      
    {$sort: {'instances.date': -1}},
    {$match: {'instances.date': {$lte: &lt;givenDate&gt;}}},
    {$project: {name: 1, _id: 0, date: "$instances.date", value: "$instances.value", score: "$instances.score"}},
    {$group: {_id: "$name", name: {$first: "$name"}, date: {$first: "$date"},
      value: {$first: "$value"}, score: {$first: "$score"}}}
  ])
  </code></pre>
  
  <p>This query works just fine, and for a given date will return the latest (that is, exactly or before the given date) instance from every document.</p>
  
  <p>My problem begins when the given date is prior to the earliest instance. For example, if my given date is 2015-03-02, I will not get any instance from <code>name1</code>. In that case, I want to retrieve the earliest instance available in the document.</p>
  
  <p>Obviously, I can split this task into two different queries and merge the results, but I would like to achieve this goal in a single DB query if possible.</p>
  
  <p>Any ideas?</p>