[英]Regex to match beginning of words in string in MongoDB
在MongoDB查询中,我试图匹配具有字符串字段的记录,该字符串字段在该字符串中任何单词的开头都包含一个搜索词。 regex在regex101.com上可以正常工作 。
/\bCh/i
匹配值:
嘉种子
我喜欢吃奇亚籽
我喜欢吃奇亚籽
但是,当我在MongoDB查询中尝试相同操作时,没有匹配记录。
{
"TenantNames" : /(\bSmith)/i
}
我也尝试了/(\\bSmith.*)/
i和/(\\bSmith.*\\b)/i
但是它们都没有返回匹配的记录。 我想念什么?
我正在使用C#驱动程序来生成查询。
这很容易通过创建文本索引并执行$ 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.