我正在使用官方C#MongoDb强类型驱动程序版本2.5.0与MongoDB进行交互。
我有以下课程Book and Page:
public class Book
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
public int PublishYear { get; set; }
public List<Page> Pages { get; set; } = new List<Page>();
}
public class Page
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int Number { get; set; }
public string HTMLContent { get; set; }
}
我的问题是:
1 - 如何在没有Pages字段的情况下查询所有图书?目前这是我的代码:
var repository = _database.GetCollection<Book>("Books");
List<Book> allBooks = await repository.Find(_ => true).ToListAsync();
2 - 如何使用id字段仅获取一本书的pages字段的title,authorName和publishYear字段?目前这是我的代码:
var repository = _database.GetCollection<Book>("Books");
var filter = Builders<Book>.Filter.Eq("Id", bookId);
Book book = await repository.Find(filter).FirstOrDefaultAsync();
3 - 如何仅将一本书的页面字段设为List<Page>
?目前这是我的代码:
var repository = _database.GetCollection<Book>("Books");
var filter = Builders<Book>.Filter.Eq("Id", bookId);
Book book = await repository.Find(filter).FirstOrDefaultAsync();
List<Page> pages = book != null ? book.Pages : new List<Page>();
答案 0 :(得分:4)
您需要Project
运营商。要仅排除特定字段,您可以这样做:
var allBooks = await repository.Find(_ => true)
.Project<Book>(Builders<Book>.Projection.Exclude(c => c.Pages))
.ToListAsync();
仅包含特定字段:
var allBooks = await repository.Find(_ => true)
.Project<Book>(Builders<Book>.Projection.Include(c => c.Pages))
.ToListAsync();
如果您需要包含\排除多个字段 - 多次调用(Include(x => x.Title).Include(x => x.Title)
等)。
仅包含您需要的替代方式:
var allBooks = await repository.Find(_ => true).Project(b => new Book {
AuthorName = b.AuthorName,
Id = b.Id,
PublishYear = b.PublishYear,
Title = b.Title
// specify what you need, don't specify what you do not
// like Pages
}).ToListAsync();