4

I've got a Visual Studio C# project that's using the MongoDB driver v2.0, and I am attempting to update it to use driver v2.3.0.

There's a section of code which builds a list of IMongoQuery entries based on the presence of various search fields, e.g.

var queryList = new List<IMongoQuery>();
if (!string.IsNullOrEmpty(searchField1))
  queryList.Add(Query.Matches(sKey1, searchField1));
...
if (!string.IsNullOrEmpty(searchFieldN))
  queryList.Add(Query.Matches(sKeyN, searchFieldN));

How do I convert this to the new FilterDefinitionBuilder syntax? I don't see a similar Add() method in its interface.

UPDATE:

Here's what I'm currently doing, and it is UGLY! Please let me know if there's a better way to do this.

var builder = Builders<BsonDocument>.Filter;
FilterDefinition<BsonDocument> filter = null;

// do this for each search field
if (!string.IsNullOrEmpty(searchField1))
{
  if (filter == null)
    filter = builder.Eq(sKey1, searchField1);
  else
    filter = filter & builder.Eq(sKey1, searchField1);
}
Alan
  • 3,715
  • 3
  • 39
  • 57
  • Please take a look here http://mongodb.github.io/mongo-csharp-driver/2.3/reference/driver/definitions/ – s7vr Mar 23 '17 at 18:31
  • Yeah, that's where I found the code to put together what I'm currently using. Thanks. – Alan Mar 23 '17 at 19:13

1 Answers1

1

I know long time passed but just in case anyone else comes here looking for a solution, here is 2.3.12 compatible way

//create a filter definition builder
var fdefb = new FilterDefinitionBuilder<BsonDocument>(); //or FilterDefinitionBuilder<TModel>
//create a list of Filter Definitions
var queryList = new List<FilterDefinition<BsonDocument>>(); //or List<FilterDefinition<TModel>> 

// do this for each search field
if (!string.IsNullOrEmpty(searchField1))
{
   if (filter == null)
       filter = fdefb.Eq(sKey1, BsonValue.Create(searchField1));
   else
       filter &= fdefb.Eq(sKey1, BsonValue.Create(searchField1));
}
Cemal
  • 1,469
  • 1
  • 12
  • 19