Justin
Justin

Reputation: 18236

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.

Upvotes: 2

Views: 2338

Answers (2)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5689

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

Upvotes: 0

Emma
Emma

Reputation: 27743

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

Upvotes: 1

Related Questions