[英]How can I get a subset of results in MongoDB C# Driver?
I have a collection of versioned documents ("rHistory"), with this structure:我有一个版本化文档(“rHistory”)的集合,具有以下结构:
{
"rid": "123e",
"v": 1
},
{
"rid": "143fe",
"v": 1
},
{
"rid": "143fe",
"v": 2
},
{
"rid": "143fe",
"v": 3
},
{
"rid": "123e",
"v": 2
}
I'm writing a function to return a subset of the documents in this collection.我正在编写 function 以返回此集合中文档的子集。 Currently I find all matching items as follows:
目前我发现所有匹配的项目如下:
_rHistory.Find(r => rIds.Contains(r.RId)).ToList()
However, I only want to return the highest versioned item of each result, like so:但是,我只想返回每个结果的最高版本项,如下所示:
{
"rid": "143fe",
"v": 3
},
{
"rid": "123e",
"v": 2
}
How can I find the newest version of each document matching a filter on rid and return the result as a list?如何在 rid 上找到与过滤器匹配的每个文档的最新版本并将结果作为列表返回? I'm assuming aggregation is involved but I'm having trouble finding relevant examples.
我假设涉及聚合,但我无法找到相关示例。 Obviously I'd rather not do this:
显然我宁愿不这样做:
foreach (var rId in rIds)
{
res.Add(_rHistory.Find(r => r.RId == rId).SortByDescending(f => f.Version).FirstOrDefault());
}
Assuming your model looks like this:假设您的 model 看起来像这样:
public class Model
{
public ObjectId Id { get; set; }
public string rid { get; set; }
public int v { get; set; }
}
You can group by rid
and return .Max()
v
:您可以按
rid
分组并返回.Max()
v
:
var col = database.GetCollection<Model>("rHistory");
var q = col.Aggregate()
.Group(
x => x.rid,
gr => new {rid = gr.Key, v = gr.Max(f => f.v)});
var result = q.ToList();
MongoDB .NET driver will translate such query into: MongoDB .NET 驱动程序会将此类查询转换为:
{ "$group" : { "_id" : "$rid", "v" : { "$max" : "$v" } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.