C # mongo 2.0 reduces FindAsync traffic

I need to get some small data from every document that I have in the database, but I still want to reduce traffic in order to prevent "Scanning the table" (just a term, I know it is not a table).

I have a collection of let say "Books" (simply because everyone uses it to give examples), now my problem is that I want only the titles of books with this author.

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); } } 

But when I look at the entire result of the collection, I use large chunks of data, right? suggests that these are not books, but entire network grids, and each document is about 5-10 MB, and I have thousands of them. Can I reduce traffic here without storing this data in another collection?

Edit I think it is called "Views" in the SQL database.

+6
source share
1 answer

You can reduce the size of returned documents using projection , which you can set in the FindOptions FindAsync parameter to include only those fields that you need:

 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); } } 

Note that the returned documents are BsonDocument objects instead of Book objects, since they contain only projected fields.

+9
source

All Articles