2016-04-14 134 views
4

我無法弄清楚如何使閱讀功能上的MongoDB在asp.net mvc的5.我在控制這部分代碼的集合:檢索對象

public HomeController() { 
      var mongoClient = new MongoClient(Settings.Default.EmployeesConnectionString); 
      var database= mongoClient.GetDatabase("football"); 
      var coll = database.GetCollection<BsonDocument>("Footballers"); 

正如你可以看到我將數據庫和收集路徑保存在一個變量中,以便更容易導航。我也對它進行了測試,我設法在mongodb中創建了一個新的集合,所以我認爲這是正確的。我的問題是我應該怎麼寫才能讓整個收藏回來?它應該在列表中嗎?之後,我會嘗試將其返回到網頁中,因此如果您對此有任何評論,請讓我知道。

+1

這可能有助於https://stackoverflow.com/questions/30453780/get-all-documents-from-mongodb-collection – JanMer

+0

ASP.NET MVC與MongoDB查詢有什麼關係? –

+1

@JanWidmer我之前看到過這個,但沒有幫助。我不是非常熟悉異步和等待方法,所以我認爲必須有另一種方式。 – Kelb56

回答

-1

獲取您導致GenericRecord像

IEnumerable的globalRelordList = MongoClient.GetDatabase( 「足球」);

代碼:

char[] commaSeperated = new char[] { ',' }; 
string[] auditRecordJSON = G.Data.Split(commaSeperated, 2); 
auditRecordDTO audit = (jsonParser.JsonDeserialize<AuditRecord>("{" +auditRecordJSON[1])); 

你GenericRecord類具有這種性質:

public class GenericRecord{} 
{ public string Id { get; set; } 
    public string Data { get; set; } 
    public string CollectionName { get; set; } 
    public RecordFormat Format { get; set; } 
} 

這裏auditRecordDTO是C#DTO具有相同的JSON字段作爲您的DTO。

+0

*讀取數據的代碼在哪裏? –

3

管理了解這一點。

var coll = database.GetCollection<BsonDocument>("Footballers"); 

     var documents = coll.Find(new BsonDocument()).ToList(); 
     for(int i=0; i<documents.Count(); i++){ 
      Console.WriteLine(documents[i]); 
     } 
     Console.ReadLine(); 

對文檔變量應用了一個簡單的for循環,並按預期打印了所有內容。

+0

如果你只想循環,你甚至不需要'ToList'。 'foreach'適用於任何Enumerable,例如'foreach(var do in documents){....}' –

1

2.x API使用異步方法。你可以使用1.x API,但可能你不想。

基本上有3種方法來檢索數據: ToListAsync()

var list = await col.Find(new BsonDocument()).ToListAsync(); 
foreach (var doc in list) 
{ 
    Console.WriteLine (doc.ToJson()); 
} 

ForEachAsync()

await col.Find(new BsonDocument()) 
    .ForEachAsync((doc,i) => { 
     Console.WriteLine ("DoC#{0}:{1}",i,doc); 
    }); 

ToCursorAsync()

using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync()) 
{ 
while (await cursor.MoveNextAsync()) 
{ 
    foreach (var doc in cursor.Current) 
    { 
    Console.WriteLine (doc.ToJson()); 
    } 
} 
} 

這裏的最後一個ToCursorAsync使用光標,我認爲這是你想要在網頁上。而不是檢索整個數據來獲取數據塊。