【发布时间】:2015-01-23 15:19:18
【问题描述】:
public class Foo
{
public ObjectId _id { get; set; }
public BsonDocument properties { get; set; }
}
public void FindFoos()
{
var client = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
var server = client.GetServer();
var db = server.GetDatabase("FooBar");
//var collection = db.GetCollection<GeoJsonFeature<GeoJson2DGeographicCoordinates>>("Sections");
var collection = db.GetCollection<Foo>("Foos");
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo1"},
{"Bar" , "bar1"}
}
});
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo2"},
{"Bar" , "bar2"}
}
});
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
var result = collection.Find(query).First();
}
调用 FindFoos 会导致以下异常:
不支持 where 子句:Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value.AsString == "foo1") ))。
说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.ArgumentException:不支持 where 子句:Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value. AsString == "foo1")))。
在线:
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
我可以在 mongodb shell 中轻松地执行此查询:
db.Foos.find( {'properties.Foo' : 'foo1'} );
使用 Linq 进行此查询的正确方法是什么?
【问题讨论】:
-
这个问题你解决了吗?我遇到了类似的问题。我有一个嵌套的复杂 BsonDocument,我需要获取所有属于某种“类型”的 BsonElement。找不到解决方案。
-
我相信我只是最终没有使用 Linq 来生成 mongodb 查询。不确定这是否随着最新版本的 mongodb c# 驱动程序而改变,但我相信我确认,当时无法使用 Linq 查询 mongodb 子文档(正如错误消息所说,这是一个不受支持的 where条款就司机而言)。
标签: c# linq mongodb-.net-driver