[英]How to use MongoDB C# Driver Aggregate to get the latest item with specific values on 2 fields?
thanks for stopping by :) 谢谢你的停止:)
Basicly, I have a MongoDB with a collection of documents with these properties: 基本上,我有一个MongoDB,其中包含具有以下属性的文档集合:
String group;
String key;
String value;
DateTime timestamp;
I want to get a list of all the most recent documents with unique (distinct) combination of group and key. 我想获得所有最新文档的列表,其中包含组和键的唯一(不同)组合。
There are documents with the same group and key but different values; 有些文件具有相同的组和键但值不同; I only want the one with the most recent timestamp.
我只想要一个具有最新时间戳的那个。
So if I have: 所以,如果我有:
Document A: Group = 2; 文件A:组= 2; Key = Something;
Key = Something; Value = 123;
值= 123; Timestamp = 20160621;
时间戳= 20160621;
Document B: Group = 2; 文件B:组= 2; Key = Something;
Key = Something; Value = 888;
值= 888; Timestamp = 20160622;
时间戳= 20160622;
I want only document B (with value 888) to be retreived in the query. 我只想在查询中检索文档B(值为888)。
This is what I got so far: 这是我到目前为止所得到的:
var aggregate = collection.Aggregate()
.Match(new BsonDocument { { "deviceid", deviceid } })
.Sort( new BsonDocument { { "timestamp", -1} })
.Group(new BsonDocument { { "groupkey", "$group" }, { "latestvalue", "$first.value" } });
This however results in the following exception: "Command aggregate failed: the group aggregate field 'groupkey' must be defined as an expression inside an object" 但是,这会导致以下异常:“命令聚合失败:必须将组聚合字段'groupkey'定义为对象内的表达式”
1) Any tips on how to use Aggregate to do what I want? 1)关于如何使用Aggregate做我想做的任何提示? (basicly, sort descending by timstamp and distinct based on 2 fields)
(基本上,按timstamp降序排序,基于2个字段分类)
2) Any tips on how to convert the aggregate to a list or similar? 2)有关如何将聚合转换为列表或类似的任何提示? (I need to use linq on all the results to find the value of a document with specific group and key)
(我需要在所有结果上使用linq来查找具有特定组和密钥的文档的值)
when using aggregation framework, as a part of training I will suggest execute same in monogo shell/robomongo to see correct syntax. 当使用聚合框架时,作为训练的一部分,我建议在monogo shell / robomongo中执行相同的操作以查看正确的语法。
Please find below fixed syntax of your query 请在下面找到您查询的固定语法
var aggregate = collection.Aggregate()
.Match(x=>x.key== "k10")
.SortByDescending(x=>x.timestamp)
.Group( BsonDocument.Parse("{ '_id':'$group', 'latestvalue':{$first:'$value'} }")).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.