从互联网上粘贴示例以查询我们的mongodb并查找字段时出现以下错误。
我看不出我做错了什么,如果我不能很快解决,我会回到SQL :(
我只想说能找到带3扇门的汽车。
感谢您的帮助!非常感谢。
连接代码
public MongoDatabase GetDatabase
{
get
{
MongoClient mc = new MongoClient();
var server = mc.GetServer();
return server.GetDatabase("players");
}
}
代码示例
var numberOfDoors = 3;
var collection = GetDatabase.GetCollection<CarCollection>("Cars");
// Have tried using my Car object instead of BsonDocument but little difference
var filter = Builders<BsonDocument>.Filter.Eq("NumberOfDoors", numberOfDoors);
var result = collection.Find(filter);
错误消息
Argument 1: cannot convert from 'MongoDB.Driver.FilterDefinition<MongoDB.Bson.BsonDocument>' to 'MongoDB.Driver.IMongoQuery'
文档结构
{
"_id" : ObjectId("..."),
"Members" : [
{
"EmailAddress" : "",
...
},
{
"EmailAddress" : "",
...
},
{
"EmailAddress" : "",
...
}
]
}
C#结构
public class MemberCollection
{
public ObjectId _id { get; set; }
public MemberEntity[] Members { get; set; }
}
public class MemberEntity
{
public int _id { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
}
更新 - 显示错误消息
文档结构
更新#2
更新3
答案 0 :(得分:1)
您错误地使用了Builders<CarCollection>.Filter.Eq()
:
var numberOfDoors = 3;
var collection = ..GetCollection<CarCollection>("Cars");
var builder = Builders<CarCollection>.Filter;
var filt = builder.Where(car => car.NumberOfDoors == numberOfDoors);
var list = await collection.Find(filt).ToListAsync();
这假定:
public class CarCollection : IEnumerable<Car> { ... }
和
public class Car { public int NumberOfDoors { get; set; } ... }
答案 1 :(得分:1)
您的以下行错误
Builders<BsonDocument>.Filter.Eq("NumberOfDoors", numberOfDoors);
它应该在下面,因为您尝试在CarCollection
上放置过滤器。这是错误的根源。
Builders<CarCollection>.Filter.Eq("NumberOfDoors", numberOfDoors);
根据您最近的编辑,您应该将过滤器定义更改为下面,因为您实际上是尝试在member
个对象的嵌套数组上放置过滤器
var filter = Builders<MemberCollection>.Filter.Eq("Members.EmailAddress", emailAddress);
等效的MongoDB查询将是
db.Getcollection('Members').Find({"Members.EmailAddress": "test@msn.com"})
修改强>
不确定你的结局有什么不对,但试试如下
var collection = _mongoclientProvider.GetDatabase.GetCollection<MemberCollection>("Members");
Expression<Func<MemberCollection, bool>> expression = mc => mc.Members.Any(m => m.EmailAddress == emailAddress);
var list = collection.Find(expression).ToList();