使用c#.net从mongodb获取数据时出错

时间:2017-12-22 07:41:00

标签: c# mongodb

string connectionString = "mongodb://10.10.32.125:27017";
        MongoClientSettings settings = MongoClientSettings.FromUrl(new 
       MongoUrl(connectionString));
        MongoClient mongoClient = new MongoClient(settings);
        var Server = mongoClient.GetDatabase("mongovaibhav");
        var collection = Server.GetCollection<employee>("mongov");


        employee cd = new employee();
        foreach (employee employess in collection.Find({ fname: "vaibhav" }) )
        {

        }

我在foreach循环和MongoCollection中收到错误。 我怎样才能获得数据列表? This error is showing

2 个答案:

答案 0 :(得分:0)

您创建了filter

var filter = Builders<employe>.Filter.Eq("fname", "vaibhav") 

然后您可以使用filter

访问您的数据

第一个选项

foreach (employee employess in 
collection.Find(filter).ToListAsync().Result )
{
  //do your computation
}

第二个选项

var employes = await collection.Find(filter).ToListAsync();
foreach(employe in employes)
{
  //do your computation
}

答案 1 :(得分:0)

 string connectionString = "mongodb://10.10.32.125:27017";
        MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
        MongoClient mongoClient = new MongoClient(settings);
        var Server = mongoClient.GetDatabase("mongovaibhav");
        var collection = Server.GetCollection<employee>("mongov");
        var filter = Builders<employee>.Filter.Eq("fname", "vaibhav");
        List<employee> emp = new List<employee>();
       foreach (var emp1 in collection.Find(filter).ToListAsync().Result )
        {
            emp.Add(emp1);
        }
        GridView1.DataSource = emp;
        GridView1.DataBind();

我得到了解决方案谢谢大家和特别的@edkeveked