我正在尝试使用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)
我完全迷失在这里。如果有必要,我可以在这里发布全班。让我知道。我顺便使用这个驱动程序:来自https://github.com/mongodb/mongo-csharp-driver/releases的CSharpDriver-1.10.0
答案 0 :(得分:0)
FindAs
希望您告诉您所期望的类型(班级),因此您必须拨打Collection.FindAs<MyClass>(query)
之类的内容。
但是,您的代码似乎比必要的复杂一点。通常更容易直接使用您的类,并使用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)。界面已完全更改 ,因此如果您现在开始,可能更容易(仅)学习新界面。