Search code examples
c#mongodbmongodb-querymongodb-.net-driver

MongoDB read document with an embedded document - c#


I successfully inserted a document using the following code:

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

But when i tried to read a record using the following code it returns an empty list:

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

Please note that when i press F10 to step over this line in debugger the cursor disappear and Fiddler shows empty results, Do I miss something?

The entities I used:

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

Solution

  • I attempted to reproduce what you are describing, but when I use F10 to step over this line of code:

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

    the result is that the value of the books variable is a List with one element in it, just as expected.

    Fiddler wouldn't show anything anyway, because it monitors HTTP traffic and the protocol between a MongoDB driver and the server is a binary protocol over a TCP socket.