mongodb C#:查询未类型化嵌套文档的值

时间:2018-10-01 20:02:14

标签: c# json mongodb querying

这是我数据库中BsonDocument的示例

{
    "employee": "A",
    "job history": [{
            "job name": "sales",
            "time": 2016
        },
        {
            "job name": "manager",
            "time": 2018,
            "location": [
                "NY",
                "OH"
            ]
        }
    ]
}

如果我需要一个简单的查询,例如“雇员姓名”,我会这样

var query = collection.Find(new BsonDocument("employee", "{}")).ToList();

现在,如果要检索“位置”的值,该怎么办?

1 个答案:

答案 0 :(得分:1)

以下是让您前进的示例:

// search by employee field
var result = collection.Find("{ 'employee': 'A' }").ToList();
Console.WriteLine(result.First()["job history"].AsBsonArray[1].AsBsonDocument["location"]); // prints [NY, OH]

// search by location
result = collection.Find("{ 'job history.location': 'NY' }").ToList();
Console.WriteLine(result.First()["employee"]); // prints A