2016-04-25 203 views
-1

我有一個mongo數據庫,其中都存儲了英文單詞。 我想獲得只包含特定字符的單詞集合。 例如:在數據庫中[ash,clash,bash,has] 要求[灰]我想要[has,ash]作爲輸出。也許有一個快速的方法,我不必建立一些特殊的數據結構。 我將在c#中進行編碼。MongoDB:如何過濾只包含特定字符的字符串?

回答

0

如果您正在使用蒙戈的淨驅動程序,然後它的LINQ實現應該是直截了當地使用。更多關於這裏的信息MONGO LINQ然後就像一些普通的IEnumerable一樣。

你的問題可能是使用正則表達式可以解決的,它可以在使用linq的Where子句中使用。正則表達式有一個很難調試的傾向,所以在這裏找到正確的正則表達式是一個替代例子(它可以進一步優化)。

private void Test() 
    { 
     // fetching from database 
     // var samples = database.GetCollection<T>"collectionname").AsQueryable<Employee>(); 
     string[] samples = new[] {"nnn", "shhhh", "has", "s", "ash"}; 
     string chars = "ash"; 
     var matches = samples.Where(x => IsMatch(x, chars)); 
    } 

    private bool IsMatch(string sample, string matchChars) 
    { 
     if (sample.Length != matchChars.Length) 
      return false; 

     sample = matchChars.Aggregate(sample, (current, c) => current.Replace(c, ' ')); 
     return sample.Trim().Length == 0; 
    } 
0

試試這個作爲查詢...我正在搜索我的身份證,它包含52C。

{ "_id": { $regex: '.*\Q52C\E.*', $options: 'i' } } 

C#等效:

await collection.Find(new BsonDocument("_id", new BsonDocument { { "$regex", $".*\Q{YourString}\E.*" }, 
                   { "$options, "i" } })).ToListAsync(); 
相關問題