简体   繁体   中英

Dynamic Query in Mongodb (C# Driver) joining dynamic criteria with AND or OR - how to?

New to mongodb

C# MongoDb.Driver version 2.2.3

I have a requirement to dynamically build up a query based on user input (eg, what data fields they would like to search on and the values of each). The query needs to allow for the operators AND/OR. For example, in SQL this query would look as follows:

Select * from products where (Brand='Gucci' AND Category='Bags') OR (Brand='Nike' AND Category='Clothing')

How can I achieve this in Mongodb using CSharp Driver?

So far I have played and tested via the Builder object:

 var filter =
            Builders<Product>.Filter.Eq("Brand", "Gucci")
            & Builders<Product>.Filter.Eq("Category", "Bags");
             var products = productRepository.Collection.Find(filter).ToList();

but not sure how to add the OR portion of the statement?

Any Help appreciated.

You can use | for OR Documentation link

var builder = Builders<Product>.Filter;
var query = builder.Eq("Brand", "Gucci") & builder.Eq("Category", "Bags")
       | builder.Eq("Brand", "D&G") & builder.Eq("Category", "Accessory");
var products = productRepository.Collection.Find(query ).ToList();

Or you can even use this way.

        var builder = Builders<Product>.Filter;
        var filter1 = builder.Eq("Brand", "Gucci") & builder.Eq("Category", "Bags");
         var filter2 =  builder.Eq("Brand", "D&G") & builder.Eq("Category", "Accessory");
         var query = builder.Or(filter1, filter2);

        var products = productRepository.Collection.Find(query).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM