我在使用C#MongoDB驱动程序构建条件查询时遇到问题。每当我运行下面的代码时,我都会得到一个空列表。任何帮助将不胜感激。
这是我的功能
public async void searchBook()
{
Book book = new Book();
IMongoDatabase mdb = MongoDBConnectionManager.ConnectToMongoDB();
var query = new BsonDocument();
if (queryString.ContainsKey("Title"))
{
query.Add("Title", queryString["Title"]);
}
if (queryString.ContainsKey("ISBN"))
{
query.Add("Isbn", queryString["ISBN"]);
}
if (queryString.ContainsKey("Author"))
{
query.Add("Author", queryString["Author"]);
}
if (queryString.ContainsKey("Publisher"))
{
query.Add("Publisher", queryString["Publisher"]);
}
var collection = mdb.GetCollection<Book>("Book");
var sort = Builders<Book>.Sort.Ascending("Title");
if(query.ElementCount > 0)
{
var list = await collection.Find(query).Sort(sort).ToListAsync();
dt = ConvertToDataTable(list);
BindGridView(dt);
}
else
{
var list = await collection.Find(Builders<Book>.Filter.Empty).Sort(sort).ToListAsync();
dt = ConvertToDataTable(list);
BindGridView(dt);
}
}
答案 0 :(得分:0)
您可以使用IMongoCollection获取您的集合,然后使用AsQueryable
var query = collection.AsQueryable();
if (!string.IsNullOrEmpty(entity.Name))
query = query.Where(p => p.Name.Contains(entity.Name));
if (!string.IsNullOrEmpty(entity.Description))
query = query.Where(p => p.Description.Contains(entity.Description));
var YourList=query.ToList();