C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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数据库中称为“视图”.

解决方法

您可以通过 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对象,因为它们只包含投影字段.

大佬总结

以上是大佬教程为你收集整理的c#mongo 2.0减少了FindAsync的流量全部内容,希望文章能够帮你解决c#mongo 2.0减少了FindAsync的流量所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。