簡體   English   中英

正則表達式匹配MongoDB中字符串中單詞的開頭

[英]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#驅動程序來生成查詢。

不確定所需的輸出是什么,我猜測您可能正在嘗試設計類似於以下內容的表達式:

.*\bChia\b.*

要么:

.*\bSmith\b.*

同樣不確定的是, i標志如何在mongodb


基於此文檔 ,也許我們可能還想使用一些不同的命令來執行此任務,例如:

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

如果您想探索/簡化/修改該表達式,請在此演示的右上面板中進行說明,如果願意,可以在此鏈接中逐步查看該表達式與某些示例輸入的匹配情況。

參考

MongoDB 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM