How to use MongoDB C# Driver Aggregate to get the latest item with specific values on 2 fields?
<p>thanks for stopping by :)</p>

<p>Basicly, I have a MongoDB with a collection of documents with these properties:</p>

<pre><code>String group;
String key;
String value;
DateTime timestamp;
</code></pre>

<p>I want to get a list of all the most recent documents with unique (distinct) combination of group and key.</p>

<p>There are documents with the same group and key but different values; I only want the one with the most recent timestamp.</p>

<p>So if I have:</p>

<p>Document A: Group = 2; Key = Something; Value = 123; Timestamp = 20160621;</p>

<p>Document B: Group = 2; Key = Something; Value = 888; Timestamp = 20160622;</p>

<p>I want only document B (with value 888) to be retreived in the query.</p>

<p>This is what I got so far:</p>

<pre><code>var aggregate = collection.Aggregate()
                .Match(new BsonDocument { { "deviceid", deviceid } })
                .Sort( new BsonDocument { { "timestamp", -1} })
                .Group(new BsonDocument { { "groupkey", "$group" }, { "latestvalue", "$first.value" } });
</code></pre>

<p>This however results in the following exception: "Command aggregate failed: the group aggregate field 'groupkey' must be defined as an expression inside an object"</p>

<p>1) Any tips on how to use Aggregate to do what I want? (basicly, sort descending by timstamp and distinct based on 2 fields)</p>

<p>2) Any tips on how to convert the aggregate to a list or similar? (I need to use linq on all the results to find the value of a document with specific group and key)</p>