mongodb Regex过滤字符串数组项目

发布于 2025-01-30 04:50:12 字数 710 浏览 3 评论 0原文

这是文档结构

{
    "_id" : ObjectId("6284f3eceae4fd4c3cfebb39"),
    "Codes" : [ 
        "Code 1",
        "Code 2",
        "Code 3"
    ]
}

,我也有Mongo查询,它可以按预期工作

{ "Codes" : { "$elemMatch" : { "$regex" : /code/, $options: 'si' } } }

,但是当我尝试使用MongoDB驱动程序编写C#代码

var filter = Builders<MyClass>.Filter
    .ElemMatch(x => x.Codes,
        Builders<string>.Filter.Regex(c => c, new BsonRegularExpression($"/^{codeFilter}/is")));

并执行此过滤器定义时,我有异常

system.invalidoperationException:'无法确定 C =&GT的序列化信息; c。'

我的错误在哪里?如何创建过滤定义以使用$ REGEX运算符检查字符串数组项目?

Here is document structure

{
    "_id" : ObjectId("6284f3eceae4fd4c3cfebb39"),
    "Codes" : [ 
        "Code 1",
        "Code 2",
        "Code 3"
    ]
}

Also i have mongo query which works as expected

{ "Codes" : { "$elemMatch" : { "$regex" : /code/, $options: 'si' } } }

But when i tried to write C# code with mongodb driver

var filter = Builders<MyClass>.Filter
    .ElemMatch(x => x.Codes,
        Builders<string>.Filter.Regex(c => c, new BsonRegularExpression(
quot;/^{codeFilter}/is")));

and execute this filter definition i've got an exception

System.InvalidOperationException: 'Unable to determine the
serialization information for c => c.'

Where is my mistake? How can i create filter definition to check string array items with $regex operator?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆沫 2025-02-06 04:50:12

您为正则构建器创建了错误的通用类型:

Builders<MyClass>.Filter.ElemMatch(
    x => x.Codes, 
    Builders<Codes>.Filter.Regex(
         c => c.Code, 
         new BsonRegularExpression($"/code/", "si")));

实体结构在哪里:

    private class MyClass
    {
        public Codes[] Codes { get; set; }
    }

    private class Codes
    {
        public string Code { get; set; }
    }

You created wrong generic type for regex builder:

Builders<MyClass>.Filter.ElemMatch(
    x => x.Codes, 
    Builders<Codes>.Filter.Regex(
         c => c.Code, 
         new BsonRegularExpression(
quot;/code/", "si")));

where the entities structure are:

    private class MyClass
    {
        public Codes[] Codes { get; set; }
    }

    private class Codes
    {
        public string Code { get; set; }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文