Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MongoDB中使用GET返回数据_Mongodb_Get_Asp.net Web Api - Fatal编程技术网

在MongoDB中使用GET返回数据

在MongoDB中使用GET返回数据,mongodb,get,asp.net-web-api,Mongodb,Get,Asp.net Web Api,我正在尝试使用Web Api连接到MongoDB,尝试使用Get返回MongoDB中连接的数据。数据库名称为“test”,集合名称为“restaurant” 这是我的密码 public IEnumerable<restaurants> Get() { var client = new MongoClient(); var dbs = client.GetDatabase("test"); var collection

我正在尝试使用Web Api连接到MongoDB,尝试使用Get返回MongoDB中连接的数据。数据库名称为“test”,集合名称为“restaurant”

这是我的密码

      public IEnumerable<restaurants> Get()
    {
        var client = new MongoClient();
        var dbs = client.GetDatabase("test");
        var collection = dbs.GetCollection<restaurants>("restaurants");


        return collection;
     }
public IEnumerable Get()
{
var client=new MongoClient();
var dbs=client.GetDatabase(“测试”);
var collection=dbs.GetCollection(“餐厅”);
回收;
}

最后一个collection单词加了下划线,我还没有找到需要返回的内容(代替collection),以便在MongoDB中显示数据库(使用postman)。

我认为您正在尝试返回IMongoCollection,而不是IEnumerable,所以最后一行加了下划线:)

尝试将集合转换为列表(异步),然后返回。例如:

public Task<List<restaurants>> GetRestaurantsAsync()
{
    var client = new MongoClient();
    var dbs = client.GetDatabase("test");
    var collection = dbs.GetCollection<restaurants>("restaurants");


    return await collection.Find(_ => true).ToListAsync();
 }


 public async Task MainAsync()
 {
    List<restaurants> restaurantsList = await GetRestaurantsAsync();
 }
公共任务GetRestaurantsAsync() { var client=new MongoClient(); var dbs=client.GetDatabase(“测试”); var collection=dbs.GetCollection(“餐厅”); return wait collection.Find(=>true).toListSync(); } 公共异步任务mainsync() { List restaurantsList=等待GetRestaurantsAsync(); }
注意:这取决于您使用的mongo c#driver的版本。

我不得不使用公共异步任务mainancy(){}方法来使用wait,我不知道如何将列表作为数组返回,似乎任务无法返回任何内容。根据您的评论,我编辑了我的答案。希望能更容易理解。