C#获取最后一个数组元素

时间:2017-07-04 09:50:50

标签: c# mongodb mongodb-query

我的藏品中有以下系列:

{
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [ 
       {
        "Report_Day": 1,
        "First_Level_Superior" : "WS66"
    }, 
    {
        "Report_Day": 2,
        "First_Level_Superior" : "CN4"
    }
},
{
    "Target_Year" : 2017,
    "Target_Month" : 7,
    "Performance" : [ 
       {
        "Report_Day": 10,
        "First_Level_Superior" : "WS66"
    }, 
    {
        "Report_Day": 11,
        "First_Level_Superior" : "CN4"
    }
}

我有代码来检索所有效果。

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Include("Performance.$");
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();

如何检索每个文档的最大Report_Day子文档而不是所有文档?

1 个答案:

答案 0 :(得分:1)

您希望此处$slice获取“最后”,即“最新”或“最大”:

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Slice("Performance",-1);
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();