我无法使用 C# 获得 MongoDB "find" 查询
I can't get a MongoDB "find" query to work using C#
我正在尝试使用 C# 为 MongoDB 数据库制作前端。
到目前为止,我已经设法使连接和插入方法正常工作。
但我一直坚持使用 find 方法,因为我是 C# 和 .net 的新手。
public void FindDocument(string query) {
BsonDocument QueryDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query);
MongoCursor result = Collection.FindAs(QueryDoc);
最后一行给我一个很长的错误:
the type arguments for the method 'MongoDB.Driver.MongoCollection.FindAs<TDocument>'(MongoDB.Driver.IMongoQuery) can't be inferrred from usage. Try to specify the type arguments explicitly)
我完全迷失在这里。如果有必要,我可以在这里post整个class。让我知道。顺便说一句,我正在使用这个驱动程序:来自 https://github.com/mongodb/mongo-csharp-driver/releases
的 CSharpDriver-1.10.0
FindAs
期望你说出你期望的 type (class),所以你必须调用类似 Collection.FindAs<MyClass>(query)
.
但是,您的代码似乎比必要的要复杂一些。直接使用 classes 并使用 QueryBuilders
创建查询通常更容易(它们也可以作为 IMongoQuery
传递给其他方法)。
class MyClass {
public ObjectId Id { get; set; }
public ObjectId UserId { get; set; }
public string Description { get; set; }
// ...
}
var coll = mongoDb.GetCollection<MyClass>("MyClass");
var result = coll.Find(Query<MyClass>.EQ(p => p.UserId == someId));
// result is now a MongoCursor<MyClass>
另外,请注意,C# 驱动程序的全新异步感知版本已经处于测试阶段(当前为 2.0.0-beta4)。界面已经完全改变,所以如果您现在开始,可能(只)更容易学习新界面。
我正在尝试使用 C# 为 MongoDB 数据库制作前端。 到目前为止,我已经设法使连接和插入方法正常工作。 但我一直坚持使用 find 方法,因为我是 C# 和 .net 的新手。
public void FindDocument(string query) {
BsonDocument QueryDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query);
MongoCursor result = Collection.FindAs(QueryDoc);
最后一行给我一个很长的错误:
the type arguments for the method 'MongoDB.Driver.MongoCollection.FindAs<TDocument>'(MongoDB.Driver.IMongoQuery) can't be inferrred from usage. Try to specify the type arguments explicitly)
我完全迷失在这里。如果有必要,我可以在这里post整个class。让我知道。顺便说一句,我正在使用这个驱动程序:来自 https://github.com/mongodb/mongo-csharp-driver/releases
的 CSharpDriver-1.10.0FindAs
期望你说出你期望的 type (class),所以你必须调用类似 Collection.FindAs<MyClass>(query)
.
但是,您的代码似乎比必要的要复杂一些。直接使用 classes 并使用 QueryBuilders
创建查询通常更容易(它们也可以作为 IMongoQuery
传递给其他方法)。
class MyClass {
public ObjectId Id { get; set; }
public ObjectId UserId { get; set; }
public string Description { get; set; }
// ...
}
var coll = mongoDb.GetCollection<MyClass>("MyClass");
var result = coll.Find(Query<MyClass>.EQ(p => p.UserId == someId));
// result is now a MongoCursor<MyClass>
另外,请注意,C# 驱动程序的全新异步感知版本已经处于测试阶段(当前为 2.0.0-beta4)。界面已经完全改变,所以如果您现在开始,可能(只)更容易学习新界面。