简体   繁体   中英

Regex to match beginning of words in string in MongoDB

In a MongoDB query, I'm trying to match records that have a string field that contains a search term at the beginning of any word in that string. The regex works correctly on regex101.com .

/\bCh/i

Matching values:

Chia seeds

i like to eat Chia seeds

i like to eat chia seeds

However when I try the same in a MongoDB query, I get no matching records.

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

I also tried /(\\bSmith.*)/ i and /(\\bSmith.*\\b)/i but they both return no matching records as well. What am I missing?

I'm using the C# driver for building queries.

Not sure, what might be the desired output, I'm guessing you may be trying to design an expression similar to:

.*\bChia\b.*

or:

.*\bSmith\b.*

Also not sure, how the i flag works in mongodb .


Based on this doc , maybe we might also want to use some different commands for this task such as:

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

The expression is explained on the top right panel of this demo , if you wish to explore/simplify/modify it, and in this link , you can watch how it would match against some sample inputs step by step, if you like.

Reference

MongoDB C# Query for 'Like' on string

this is quite easily achieved by creating a text index and doing a $text search.

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

here's the c# code that generated the above queries. it uses my library MongoDB.Entities for brevity.

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM