[英]MongoDB C# List the latest of all entries on a sub document
Is it possible to list all the restaurants and their latest grade, if grades is a an array within a restaurant? 如果等级是餐厅中的一个数组,是否可以列出所有餐厅及其最新等级?
{
"_id" : ObjectId("56bf7957b5e096fd06b755b2"),
"grades" : [
{
"date" : ISODate("2014-11-15T00:00:00.000Z"),
"grade" : "Z",
"score" : 38
},
{
"date" : ISODate("2014-05-02T00:00:00.000Z"),
"grade" : "A",
"score" : 10
},
{
"date" : ISODate("2013-03-02T00:00:00.000Z"),
"grade" : "A",
"score" : 7
},
{
"date" : ISODate("2012-02-10T00:00:00.000Z"),
"grade" : "A",
"score" : 13
}
],
"name" : "Brunos On The Boulevard",
}
I would want to get: 我想要得到:
{
"_id" : ObjectId("56bf7957b5e096fd06b755b2"),
"grades" : [
{
"date" : ISODate("2014-11-15T00:00:00.000Z"),
"grade" : "Z",
"score" : 38
}
],
"name" : "Brunos On The Boulevard",
}
Explanation 说明
The answer below uses the unwind operator . 下面的答案使用unwind运算符 。 There's a really simple explanation of it on this answer , should anyone be confused by it as I was.
如果有人像我一样对它感到困惑,那么这个答案有一个非常简单的解释。
An option could be doing an aggregate with two operations, an Unwind
which deconstructs your array field from the input documents to output a document for each element, and later a sort operation by date
in descending order. 一个选项,可以做两个业务,一个聚集
Unwind
它解构了您的阵列从外地输入文档输出为每个元素由文档,后来排序操作date
降序排列。 This way you can get the result you are expected selecting the first element from the aggregate result: 这样,您可以得到期望的结果,从合计结果中选择第一个元素:
var result = collection.Aggregate()
.Unwind(e => e["grades"])
.SortByDescending(e=>e["grades.date"])
.FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.