2015-09-17 83 views
3

我有一個FilterDefinition構建,它將查找基於非空屬性的地址。C#Mongo查詢效率

public static FilterDefinition<TU> FindPointByAddress<TU>(Address address) 
{ 
    var filterBuilder = Builders<TU>.Filter; 
    var filterItems = new List<FilterDefinition<TU>>(); 

    if (!String.IsNullOrWhiteSpace(address.Street)) 
    { 
     filterItems.Add(filterBuilder.Eq("Address.Street", address.Street)); 
    } 

    if (!String.IsNullOrWhiteSpace(address.City)) 
    { 
     filterItems.Add(filterBuilder.Eq("Address.City", address.City)); 
    } 

    if (!String.IsNullOrWhiteSpace(address.StateProvince)) 
    { 
     filterItems.Add(filterBuilder.Eq("Address.StateProvince", address.StateProvince)); 
    } 

    if (!String.IsNullOrWhiteSpace(address.PostCode)) 
    { 
     filterItems.Add(filterBuilder.Eq("Address.PostCode", address.PostCode)); 
    } 

    return filterBuilder.And(filterItems); 
} 

IMO此查詢感覺髒,有沒有更好的方法來建立這種類型的查詢或這是正確的方式?

回答

3

前幾天我有類似的情況。我寫了一個簡單的方法,它將字段名稱和字段值作爲字符串。

public void AddEqualCompareFilter(string fieldName, string fieldValue) 
    { 
     if (String.IsNullOrEmpty(fieldValue) == false) { 
      if (Filter != null) { 
       Filter = Filter & Builders<TranslationsDocument>.Filter.Eq(fieldName, fieldValue); 
      } 
      else { 
       FilterCount++; 
       Filter = Builders<TranslationsDocument>.Filter.Eq(fieldName, fieldValue); 
      } 

     } 
    } 

我然後用這個片段,以決定基於FilterCount:

if (FilterCount > 0) { 
      Result = collection.Find(Filter).ToListAsync().GetAwaiter().GetResult(); 
      return true; 
     } 
     else { 

      Result = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult(); 
      return true; 
     }