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

时间:2017-12-27 11:09:18

标签: c# mongodb

我正在尝试实现非常简单的算法。 假设我们有一些简单的层次结构: (根)A => B => C 每个nove代表一些ID,每个ID包含许多记录。

记录有:  (字符串)Id和(List)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 = []}

现在算法看起来像:

如果我想从C中取记录,我需要: C,B,A存在于Id AND中 C,B,A不存在于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是List。结果:

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

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

异常指向ts =&gt; ts.ExcludedScenarioGuids

EDIT2:

如@cloudikka所写,解决方案是AnyNin和In。感谢

1 个答案:

答案 0 :(得分:2)

您可能希望使用In方法而不是Where方法。或者,Nin方法。两者都可以用于单个值字段。对于数组字段,还有AnyIn和相对AnyNin

相关来源:

In method

Nin method

AnyIn method

AnyNin method