簡體   English   中英

MongoDB C#驅動程序->檢查字符串是否包含列表中的元素(字符串)

[英]MongoDB C# Driver -> Check if a string contains an element from a list (of strings)

我正在嘗試實現相當簡單的算法。 假設我們有一些簡單的層次結構:(根)A => B => C每個nove代表一個ID,每個ID包含許多記錄。

記錄有:(字符串)Id和(列表)ExcludedId

所以我們可以有:

rec1:{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中獲取記錄,則需要獲取:ID中存在C,B,A,而ExcludedId中不存在C,B,A

所以我寫道:

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的異常

編輯2:

如@cloudikka所寫,解決方案是AnyNin和In。 謝謝

您可能要使用In方法而不是Where方法。 或者, Nin法。 兩者都可以用於單個值字段。 數組字段也有AnyIn和相對的AnyNin

相關資料:

在方法中

寧法

AnyIn方法

AnyNin方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM