我必须从数据库中的每个文档中获取一些次要数据,但我仍然希望减少通信量,以防止“表扫描”(术语,我知道它不是表)。
我有一个集合,让我们说“书籍”(只是因为每个人都用它来举例),现在,我的问题是,我只想要图书标题与给定的作者。
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左右,而且我有数千个them..how --我可以在这里减少通信量吗?不需要将这些数据存储在另一个集合中?
编辑我认为它在SQL数据库中被称为“视图”。
发布于 2015-10-05 01:53:35
您可以通过projection缩小返回文档的大小,您可以在FindAsync的FindOptions参数中设置它,使其只包含所需的字段:
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对象,因为它们只包含投影字段。
发布于 2019-11-14 11:54:59
除了接受的答案之外,还可以将表达式应用于转换目的的投影,该表达式的工作方式类似于Linq的.Select()方法:
var projection = Builders<Page>.Projection.Expression(x => new Page { Title = x.Title });https://stackoverflow.com/questions/32938656
复制相似问题