2017-12-27 227 views
0

我試圖實現相當簡單的算法。假設我們有一些簡單的層次結構: (root)A => B => C 每個nove代表一些ID,每個ID包含許多記錄。MongoDB C#驅動程序 - >檢查一個字符串是否包含一個列表中的元素(字符串)

記錄有: (串)Id和(名單)ExcludedId

所以我們可以有:

REC 1:{ID:A; ExcludedId = [B]}

rec2:{Id:A; ExcludedId = [D]}

rec3:{Id:A; ExcludedId = [B]}

rec1':{Id:A; ExcludedId = []}

REC1" :{ID:C; ExcludedId = []}

REC2' :{ID:d; ExcludedId = []}

現在算法看起來像:

如果我想借此記錄從CI需要考慮: C,B,A ID和 C,B存在,不存在ExcludedId

所以我寫了:

public List<Record> GetRecords(string id, List<string> parentId) 
{ 
    if (parentsIds == null) 
      parentsIds = new List<string>(); 

    var collection = _mongoDbConnection.GetCollection<Records>(); 

    var allScenarios = parentsIds.ToList(); 
    allScenarios.Add(Id); 

    var myfilter = Builders<Record>.Filter.And(
      Builders<Record>.Filter.Where(record => allScenarios.Any(s => record.Id.Contains(s))), 
      Builders<Record>.Filter.Not(Builders<Record>.Filter.Where(record => allScenarios.Any(s => record.ExcludedIds.Contains(s)))) 
     ); 

return collection.Find(myfilter).ToList(); 
} 

但是我收到一個異常,說:

Unsupported filter: Any(value(System.Collections.Generic.List`1[System.String]).Where({document}{Id}.Contains({document}))).' 

你能幫助我嗎?謝謝你在前進

編輯:

更改:

Builders<Record>.Filter.Where(record => allScenarios.Any(s => record.Id.Contains(s)) 

Builders<Record>.Filter.In(ts => ts.ScenarioGuid, parentScenarioGuids), 

這作品!但我有問題

Builders<Record>.Filter.Not(Builders<Record>.Filter.Where(record => allScenarios.Any(s => record.ExcludedIds.Contains(s)))) 
     ); 

因爲ExcludedIds是列表。其結果是:

Builders<Record>.Filter.Nin(ts => ts.ExcludedScenarioGuids, allScenarios) 

Cannot convert lambda expression to type FieldDefinition<Records, string> because it not a delegate type. 

異常指向TS => ts.ExcludedScenarioGuids

EDIT2:

如@cloudikka寫道,溶液是AnyNin和在。謝謝

回答

2

您可能需要使用In方法而不是Where方法。或者,Nin方法。兩者都可以用於單個值字段。對於數組字段,還有AnyInAnyNin

相關來源:

In method

Nin method

AnyIn method

AnyNin method

+0

謝謝!部分解決了我的問題。但我仍然有問題,我寫在我的問題(我編輯後)。你能再幫忙嗎? –

+0

我敢打賭,它是數組字段,在這種情況下,您必須使用[AnyNin方法](http://mongodb.github.io/mongo-csharp-driver/2.5/apidocs/html/M_MongoDB_Driver_FilterDefinitionBuilder_1_AnyNin__1.htm) – cloudikka

+0

謝謝!幾分鐘前我發現了任何一個。但基本上 - 你的答案幫助了我。 –

相關問題