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

时间:2015-05-09 13:29:39

标签: c# mongodb mongodb-query mongodb-.net-driver

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

 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();
}

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

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; }
}

1 个答案:

答案 0 :(得分:0)

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

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

结果是books变量的值是一个List,其中包含一个元素,正如预期的那样。

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