C# 我能';“我得不到MongoDB”;查找“;使用C查询工作#
我正在尝试使用C#为MongoDB数据库制作前端。 到目前为止,我已经设法使连接和insert方法正常工作。 但我一直坚持使用find方法,因为我对C#和.net一般来说都是新手C# 我能';“我得不到MongoDB”;查找“;使用C查询工作#,c#,visual-studio,mongodb,C#,Visual Studio,Mongodb,我正在尝试使用C#为MongoDB数据库制作前端。 到目前为止,我已经设法使连接和insert方法正常工作。 但我一直坚持使用find方法,因为我对C#和.net一般来说都是新手 public void FindDocument(string query) { BsonDocument QueryDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query);
public void FindDocument(string query) {
BsonDocument QueryDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query);
MongoCursor result = Collection.FindAs(QueryDoc);
公共作废FindDocument(字符串查询){
BsonDocument QueryDoc=MongoDB.Bson.Serialization.BsonSerializer.Deserialize(查询);
MongoCursor结果=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)
无法从用法推断方法“MongoDB.Driver.MongoCollection.FindAs”(MongoDB.Driver.imongquery)的类型参数。请尝试显式指定类型参数)
我在这里完全迷路了。如果有必要,我可以在这里发布整个类。让我知道。我正在使用这个驱动程序:CSharpDriver-1.10.0 from
FindAs
期望您告诉您期望的类型(类),所以您必须调用类似于Collection.FindAs(query)
的东西
但是,您的代码似乎有点过于复杂。直接使用类并使用QueryBuilders
创建查询通常更容易(它们也可以作为IMongoQuery
传递给其他方法)
class-MyClass{
公共对象Id{get;set;}
public ObjectId UserId{get;set;}
公共字符串说明{get;set;}
// ...
}
var coll=mongoDb.GetCollection(“MyClass”);
var result=coll.Find(Query.EQ(p=>p.UserId==someId));
//结果现在是一个MongoCursor
另外,请注意,C#driver的一个全新的、支持异步的版本已经在beta版中(目前为2.0.0-beta4)。该接口已经完全更改,因此如果您现在开始使用,可能更容易(仅)学习新接口。我将代码更改为:
public void FindDocument(字符串查询){var result=Collection.Find(Query.EQ(p=>p.TERM==Query));
我的文档的形状是这样的(我正在制作一本字典):{TERM:“面向对象编程”,定义:“编程范例”}我有一个类似于您提供的类示例(但有适当的字段)作为MyClass。现在它给了我一个不同的错误:它告诉我没有Find方法。我使用ctrl+spacebar,只显示FIndAs及其相关项。如果我使用它,同样的错误会出现:无法从用法推断,等等。我决定遵循mnemosyn的想法,等待新的mongo驱动程序。新的API当然更简单。谢谢你的answ呃:)
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>