title: Find maximal value for field in all collections
body: <p>I have an database containing collections, and these collections containing documents on the form:</p>
  
  <pre><code>{ "_id" : 4, "value" : 2 }
  </code></pre>
  
  <p>I want to find the maximum <code>"_id"</code> in all the collections in a efficient way. At the moment, I have a working method:</p>
  
  <pre><code>public long getLastTimestamp()
  {
      var tempList = getChannelNames();
      var channelList = new List&lt;IMongoCollection&lt;BsonDocument&gt;&gt;();
      var docuList = new List&lt;BsonDocument&gt;();
  
      foreach (var channel in tempList)
      {
          channelList.Add(_database.GetCollection&lt;BsonDocument&gt;(channel.name));
      }
  
      foreach (var channel in channelList)
      {
          var filter = Builders&lt;BsonDocument&gt;.Filter.Exists("_id");
          var result = channel.FindAsync(filter).Result.ToList();
  
          foreach (var docu in result)
          {
              docuList.Add(docu);
          }
      }
  
      var timeList = new List&lt;long&gt;();
  
      foreach (var docu in docuList)
      {
          Console.WriteLine(docu);
          if (!docu["_id"].IsObjectId)
              timeList.Add(docu["_id"].ToInt64());
      }
  
      return timeList.Max();
  }
  </code></pre>
  
  <p>It works, but I don't think it's very efficient.
  Does anyone have some input or advice?</p>
  
  <p>EDIT:
  I ended up doing this:</p>
  
  <pre><code>    public long getLastTimestamp()
      {
          var filter = Builders&lt;BsonDocument&gt;.Filter.Exists("value");
          return getChannelNames()
              .Select(channel =&gt; _database.GetCollection&lt;BsonDocument&gt;(channel.name))
              .SelectMany(channel =&gt; channel.FindAsync(filter).Result.ToList())
              .Max(docu =&gt; docu["_id"].ToInt64());
      }
  </code></pre>