MongoDB 使用嵌入式文档读取文档 - c#

MongoDB read document with an embedded document - c#

我使用以下代码成功插入了文档:

 public async Task<List<Book>> ListBooks(BooksSearchFilter booksSearchFilter)
        {

    _client = new MongoClient(); //ConfigurationManager.AppSettings["MongoConnection"]
    _db = _client.GetDatabase(ConfigurationManager.AppSettings["MongoDatabaseName"]);

    var collection = _db.GetCollection<Book>("book");

    Publisher p = new Publisher { 
        Name = "O'Reilly Media", 
        Founded = 1980, 
        Location = "CA" };
    Book bookTest = new Book { 
        Language = "English", 
        Pages = 68, 
        PublishedDate = DateTime.Now, 
        Publisher = p, 
        Title = "MongoDB: The Definitive Guide" };
    bookTest.Author = new List<string>();
    bookTest.Author.Add("auth1");
    await collection.InsertOneAsync(bookTest);

    var books = await collection.Find(b => b.Language =="English").ToListAsync();
}

但是当我尝试使用以下代码读取记录时,它 returns 是一个空列表:

var books = await collection.Find(b => b.Language == "English").ToListAsync();

请注意,当我在调试器中按 F10 跨过这一行时,光标消失并且 Fiddler 显示空结果,我错过了什么吗?

我使用的实体:

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string  Id { get; set; }

    //[BsonElement("title")]
    public string Title { get; set; }

    //[BsonElement("author")]
    public List<string> Author { get; set; }

    //[BsonElement("published_date")]
    public DateTime PublishedDate { get; set; }

    //[BsonElement("pages")]
    public double Pages { get; set; }

    //[BsonElement("language")]
    public string Language { get; set; }

    //[BsonElement("publisher")]
    public Publisher Publisher { get; set; }

}

public class Publisher
{
    //[BsonElement("name")]
    public string Name { get; set; }

    //[BsonElement("founded")]
    public double Founded { get; set; }

    //[BsonElement("location")]
    public string Location { get; set; }
}

我试图重现您所描述的内容,但是当我使用 F10 跳过这行代码时:

var books = await collection.Find(b => b.Language == "English").ToListAsync();

结果是 books 变量的值是一个列表,其中有一个元素,正如预期的那样。

Fiddler 无论如何都不会显示任何内容,因为它监视 HTTP 流量,并且 MongoDB 驱动程序和服务器之间的协议是基于 TCP 套接字的二进制协议。