【发布时间】:2015-05-09 13:29:38
【问题描述】:
我使用以下代码成功插入了一个文档:
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; }
}
【问题讨论】:
-
您是否尝试过使用“Where”而不是“Find”?
-
集合类中没有这样的方法,我使用的是最新的c#驱动程序2.0版。现在所有方法都是异步的。
-
- 你能从 shell 中发布藏书的内容吗? db.book.find().pretty()? - Fiddler 是一个 HTTP 嗅探器。 MongoDB 不使用 HTTP,而是使用 TCP。 Fiddler 永远不会看到任何 MongoDB 流量。
-
yes db.book.find().pretty() 返回结果,我认为问题是因为上面的代码在一个标记为异步的方法内部,可能是它返回控制给调用者(Web API) 在完成抓取任务之前。 public async Task
- > ListBooks(BooksSearchFilter booksSearchFilter) {>}
-
如果
books已经是一个列表,那么调用已经返回。该列表不会延迟填充(与IAsyncCursor不同),因此一旦您拥有该列表,它就与调用的异步性没有任何关系。你真的到了可以检查列表的地步吗?在 mongodb 中启用查询日志记录(通过集成分析器)以查看查询是否被服务器接收并包含您期望的内容。
标签: c# mongodb mongodb-query mongodb-.net-driver