【发布时间】:2018-09-18 20:49:34
【问题描述】:
我正在使用官方的 C# MongoDb 强类型驱动程序 2.5.0 版本与 MongoDB 进行交互。
我的 Book 和 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-如何在没有单本书的 pages 字段的情况下使用 id 字段获取 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-如何仅将一本书的 pages 字段作为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>();
【问题讨论】:
标签: c# .net mongodb mongodb-query mongodb-.net-driver