Chee Mun
Chee Mun

Reputation: 85

C# Get last Array Element

I has the following collection in my collection:

{
    "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"
    }
}

I has the codes to retrieve all Performance.

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();

How can I retrieve the max Report_Day sub document for each document instead of all documents?

Upvotes: 1

Views: 901

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You want $slice here to get the "last" which is the "latest" or "max":

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();

Upvotes: 1

Related Questions