【问题标题】:MongoDB C# Driver -> Check if a string contains an element from a list (of strings)MongoDB C# Driver -> 检查字符串是否包含列表中的元素(字符串)
【发布时间】:2017-12-27 11:09:18
【问题描述】:

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

记录有: (string) Id 和 (List)ExcludedId

所以我们可以:

rec1:{ ID: A;排除 ID = [B]}

rec2:{ ID: A;排除 ID = [D]}

rec3:{ ID: A;排除 ID = [B]}

rec1':{ ID: A;排除 ID = []}

rec1":{ Id: C; ExcludedId = []}

rec2':{ ID: D;排除 ID = []}

现在算法看起来像:

如果我想从 C 中获取记录,我需要获取: C,B,A 存在于 Id AND C,B,A NOT 存在于 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 => ts.ExcludedScenarioGuids

编辑2:

如@cloudikka 写的,解决方法是AnyNin 和In。谢谢

【问题讨论】:

    标签: c# mongodb


    【解决方案1】:

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

    相关来源:

    In method

    Nin method

    AnyIn method

    AnyNin method

    【讨论】:

    • 谢谢!部分解决了我的问题。但是我在我的问题中写的 Nin 仍然有问题(我编辑了帖子)。你能再帮忙吗?
    • 我打赌它是数组字段,在这种情况下你必须使用AnyNin method
    • 谢谢!几分钟前我找到了anyNin。但基本上 - 你的回答帮助了我。
    • 我将使用 AnyIn 和 AnyNin 更新答案!乐于助人。编码愉快!
    猜你喜欢
    • 2010-10-04
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2020-02-26
    • 1970-01-01
    • 2021-12-20
    • 2019-04-11
    相关资源
    最近更新 更多