Chee Mun
Chee Mun

Reputation: 85

C# Mongo retrieve sub document

I has the following documents in my collection:

{
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [ 
       {
        "Report_Day": 1,
        "First_Level_Superior" : "WS66",
        "Second_Level_Superior" : "SB23"
    }, 
    {
        "Report_Day": 2,
        "First_Level_Superior" : "CN4",
        "Second_Level_Superior" : "WS66"
    }, 
    {
        "Report_Day": 3,
        "First_Level_Superior" : "",
        "Second_Level_Superior" : "TN27"
    }]
}

The following is my current filtering codes:

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017") & builder.Eq("Target_Month", "6") & builder.Eq("Performance.Report_Day", "1");
var result = mongoDB.Performance.Find(filterMain).FirstOrDefault();

What I need to retrieve actually is just:

    {
        "Report_Day": 1,
        "First_Level_Superior" : "WS66",
        "Second_Level_Superior" : "SB23"
    }

OR

 {
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [ { 
        "Report_Day": 1,
        "First_Level_Superior" : "WS66",
        "Second_Level_Superior" : "SB23"
    }]
}

Any help is really greatly appreciated.

Upvotes: 2

Views: 1705

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You need to add a "projection" with the positional $ operator to reference the matched array item from the query conditions:

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017") & builder.Eq("Target_Month", "6") &
    builder.Eq("Performance.Report_Day", "1");
var project = Builders<BsonDocument>.Projection.Include("Performance.$");

var result = mongoDB.Performance.Find(filterMain).Project(project).FirstOrDefault();

The $ represents the "index" of the array which was matched in the query expression with:

builder.Eq("Performance.Report_Day", "1");

Upvotes: 2

Related Questions