2015-10-04 53 views
5

的交通我得從每個文檔我在數據庫中,但我還是想減少流量,以防止「表掃描」一些小的數據(只是術語,我知道它不表) 。C#MONGO 2.0降低FindAsync

我的收藏可以說「書」(只是因爲每個人都用它來給舉例),現在,我的問題是,我想只給作者的書名。

var filter = Builders<Book>.Filter.Eq(n => n.Author, AuthorId); 

      List<string> books = new List<string>(); 

      using (var cursor = await BooksCollection.FindAsync(filter)) 
      { 
       while (await cursor.MoveNextAsync()) 
       { 
        var batch = cursor.Current; 
        foreach (Book b in batch) 
         books.Add(b.Title); 
       } 
      } 

但是,當我掃描整個收集結果時,我正在使用大塊數據,不是嗎?讓我們假設這些不是書籍,而是整個網格網絡,每個文檔大約5-10 MB,並且我有成千上萬個..如何在不將這些數據存儲在另一個集合中的情況下減少流量?

編輯 我認爲它在SQL數據庫中被稱爲「視圖」。

回答

8

您可以通過projection您可以在FindOptions參數FindAsync只設定減少返回文檔的大小包括你所需要的字段:

var filter = Builders<Book>.Filter.Eq(n => n.Author, AuthorId); 
// Just project the Title and Author properties of each Book document 
var projection = Builders<Book>.Projection 
    .Include(b => b.Title) 
    .Include(b => b.Author) 
    .Exclude("_id"); // _id is special and needs to be explicitly excluded if not needed 
var options = new FindOptions<Book, BsonDocument> { Projection = projection }; 

List<string> books = new List<string>(); 

using (var cursor = await BooksCollection.FindAsync(filter, options)) 
{ 
    while (await cursor.MoveNextAsync()) 
    { 
     var batch = cursor.Current; 
     foreach (BsonDocument b in batch) 
      // Get the string value of the Title field of the BsonDocument 
      books.Add(b["Title"].AsString); 
    } 
} 

注意,返回文件BsonDocument對象,而不是Book對象,因爲它們只包含投影字段。