1

I am having trouble building a conditional query using C# MongoDB driver. Whenever I run the code below, I get an empty list. Any help will be greatly appreciated.

Here is my function

 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);
        }                                
    }
1
  • 1
    what happens when you actually step through the code using the debugger..? what are the values of the queryString can you at least show us that..? also you could convert the if conditional statement to use a switch(){ case } statement.. you need to provide more information.. Commented Apr 20, 2016 at 16:23

1 Answer 1

1

You can use IMongoCollection to get your collection and then use 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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.