MongoDB C#驱动程序 - >检查一个字符串是否包含一个列表中的元素(字符串)

问题描述:

我试图实现相当简单的算法。假设我们有一些简单的层次结构: (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和在。谢谢

您可能需要使用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

谢谢!几分钟前我发现了任何一个。但基本上 - 你的答案帮助了我。 –