【问题标题】:Regex to match beginning of words in string in MongoDB正则表达式匹配 MongoDB 中字符串中单词的开头
【发布时间】:2019-07-11 20:19:11
【问题描述】:

在 MongoDB 查询中,我尝试匹配具有字符串字段的记录,该字符串字段在该字符串中任何单词的开头包含搜索词。正则表达式在 regex101.com 上正常工作。

/\bCh/i

匹配值:

奇亚籽

我喜欢吃奇亚籽

我喜欢吃奇亚籽

但是,当我在 MongoDB 查询中尝试相同的操作时,我没有得到匹配的记录。

{
    "TenantNames" : /(\bSmith)/i
}

我也尝试了/(\bSmith.*)/i 和/(\bSmith.*\b)/i,但它们也都没有返回匹配的记录。我错过了什么?

我正在使用 C# 驱动程序来构建查询。

【问题讨论】:

  • 调试这个的好方法是使用正则表达式. 然后如果它不匹配,那么它不是正则表达式对吗?这将是你的语言所期望的用法、引用和形式。类似的东西。
  • @sln 。作品。我得到的最接近的是 /(?=.*Ch)/i,但它会返回任何在单词的任何部分而不是开头都具有值“ch”的字符串,因此返回的结果太多。
  • 你试过{ TenantNames: { $regex: /\bCh/i } 吗? docs.mongodb.com/manual/reference/operator/query/regex

标签: c# regex mongodb mongodb-query


【解决方案1】:

不确定,可能需要什么输出,我猜您可能正在尝试设计一个类似于以下内容的表达式:

.*\bChia\b.*

或:

.*\bSmith\b.*

也不确定i 标志在mongodb 中的工作原理。


基于this doc,也许我们还想为此任务使用一些不同的命令,例如:

{ name: { $regex: /.*\bSmith\b.*/, $options: 'i', $nin: [ 'TenantNames' ] } }

表达式在this demo 的右上角进行了解释,如果您想探索/简化/修改它,在this link 中,您可以逐步观察它如何与一些示例输入匹配,如果你喜欢。

参考

MongoDB C# Query for 'Like' on string

【讨论】:

  • @Emma "TenantNames" : /.*\bCh\b.*/i 返回 0 个结果。让我试试其他格式,我正在使用 C# 驱动程序来构建查询,但希望他们有办法生成这种格式。
  • 我无法使用 C# 驱动程序生成该格式。尝试了 builder.Regex(z => z.TenantNames, new BsonRegularExpression(regexString, "i")) 和 new BsonDocument { { "TenantNames", new BsonDocument { { "$regex", regexString }, { "$options", “一世” } } } };但它仍然转换为“TenantNames”:/.*\bCh\b.*/i
【解决方案2】:

这很容易通过创建文本索引并执行$text 搜索来实现。

db.Property.createIndex({"TenantNames": "text"},{"background":false})
db.Property.find({
    "$text": {
        "$search": "smith",
        "$caseSensitive": false
    }
})

这是生成上述查询的 c# 代码。为简洁起见,它使用我的库 MongoDB.Entities。

using MongoDB.Entities;
using System;

namespace StackOverflow
{
    public class Program
    {
        public class Property : Entity
        {
            public string TenantNames { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test");

            DB.Index<Property>()
              .Key(p => p.TenantNames, KeyType.Text)
              .Option(o => o.Background = false)
              .Create();

            (new[] {
                new Property { TenantNames = "Maggie Smith" },
                new Property { TenantNames = "Smith Clein" },
                new Property { TenantNames = "marcus smith stein" },
                new Property { TenantNames = "Frank Bismith" }
            }).Save();

            var result = DB.SearchText<Property>("smith");

            foreach (var property in result)
            {
                Console.WriteLine(property.TenantNames);
            }

            Console.Read();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2018-11-23
    相关资源
    最近更新 更多