[英]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.