C#Mongo检索子文档

时间:2017-06-28 08:02:36

标签: c# mongodb

我的收藏中有以下文件:

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

以下是我目前的过滤代码:

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

我需要检索的只是:

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您需要添加"projection" positional $ operator来引用查询条件中匹配的数组项:

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

$表示在查询表达式中匹配的数组的“索引”:

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