这些是我的实体;
class User
{
[BsonId]
public string Id { get; set; }
public string name { get; set; }
public List<Address> Adress { get; set; }
}
class Address
{
[BsonId]
public string Id { get; set; }
public string AddressName { get; set; }
public string AddressDetail { get; set; }
}
我的插入代码到mongo db如下,没有问题。
const string uri = "mongodb://usermehmet:inno12345@localhost/testDB";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
counter++;
User user=new User();
user.Id = ObjectId.GenerateNewId().ToString();
user.name = counter+"user";
user.Adress = new List<Address>();
Address a1=new Address();
a1.Id = ObjectId.GenerateNewId().ToString();
a1.AddressName = "Ev";
a1.AddressDetail = "a sokak b caddesi c no d kat";
Address a2=new Address();
a2.Id = ObjectId.GenerateNewId().ToString();
a2.AddressName = "İş";
a2.AddressDetail = "x sokak y caddesi z no f kat";
user.Adress.Add(a1);
user.Adress.Add(a2);
var collection2 = db.GetCollection<User>("Users");
collection2.Insert(user);
但我从mongodb网站(Query an Array for an Element¶)获取的查询操作是在var result = collection.Find(filter).ToList();
行创建编辑器错误。
const string uri = "mongodb://usermehmet:inno12345@localhost/testDB";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection<User>("Users");
var filter = Builders<User>.Filter.Eq("name", "100user");
var result = collection.Find(filter).ToList();
错误:
无法从MongoDB.Driver.FilterDefinition ConsoleApplication14.User转换为MongoDB.Driver.IMongoQuery
答案 0 :(得分:3)
从GetServer()
调用中可以看出,您可能正在使用较早版本的MongoDB .NET驱动程序。在旧API中,Find()
函数需要IMongoQuery
过滤器定义。
尝试更新MongoDB.Driver NuGet。如果我没弄错的话,最新的是v2.5。
答案 1 :(得分:0)
我通过mongo db new api方法解决了问题,问题是GetServer,因为它已经过时了。
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl("mongodb://usermehmet:inno12345@localhost/testDB"));
var mongoClient = new MongoClient(settings);
_database = mongoClient.GetDatabase("testDB");
var collection=_database.GetCollection<User>("Users");
var result = collection.Find(x=>x.name=="100user").ToList();