在Mongo DB驱动程序C#中使用$ in子句进行不敏感搜索

时间:2019-05-27 22:51:24

标签: c# mongodb mongodb-query mongodb-.net-driver

我想知道如何对$ in表达式使用不区分大小写的内容。

根据MongoDB官方手册,您可以执行以下操作:

{ name: { $in: [ /^acme/i, /^ack/ ] } }

我在Compass上进行了测试,它工作正常,搜索不敏感。

我需要使用C#中的Mongo驱动程序。

我正在这样做:

  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();

companyNames是一个字符串[]

但是,这只会检索到我完全匹配的内容。这很明显,因为我没有包括“ regex”表达式。但是我不知道如何将正则表达式包含在字符串中。

解决方法是为每个公司名称使用正则表达式创建$或表达式。

有人知道该怎么做吗?

谢谢

3 个答案:

答案 0 :(得分:1)

使用mongo-csharp-driver,您可以使用MongoDB.Bson.BsonRegularExpression。您可以执行:

var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression("^acme", "i")
                  ).Add(
                      new BsonRegularExpression("^ack"));
var filter = new BsonDocument { { "name", new BsonDocument { { "$in", arrayIn }} } };
var cursor = collection.Find(filter).ToList();

或者,也可以使用RegexRegexOptions代替string

var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression(
                          new Regex(
                              "^acme", RegexOptions.IgnoreCase))
                  ).Add(new BsonRegularExpression(
                              "^ack"));

答案 1 :(得分:0)

这是在公司名称字段上使用文本索引的一种优雅解决方案。

using MongoDB.Entities;

namespace StackOverflow
{
    class Program
    {
        public class Company : Entity
        {
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {
            new DB("test");

            DB.Index<Company>()
              .Key(c => c.Name, KeyType.Text)
              .Option(o => o.Background = false)
              .Create();

            var c1 = new Company { Name = "Ackme" };
            var c2 = new Company { Name = "Acme" };
            var c3 = new Company { Name = "Lackme" };
            var c4 = new Company { Name = "Hackme" };

            c1.Save(); c2.Save(); c3.Save(); c4.Save();

            var names = new[] { "ackme", "acme" };

            var result = DB.SearchText<Company>(string.Join(" ", names));
        }
    }
}

请注意,以上内容使用便利性库MongoDB.Entities。但是,概念是相同的,但与上述相比,正式驱动程序的语法繁琐。

答案 2 :(得分:0)

我的解决方案是将重载.In()作为扩展方法,并采用了不区分大小写的额外参数:

public static class MongoExtensions
{
    public static FilterDefinition<TDocument> In<TDocument>(
        this FilterDefinitionBuilder<TDocument> builder,
        Expression<Func<TDocument, object>> expr,
        IEnumerable<string> values,
        bool ignoreCase)
    {
        if (!ignoreCase)
        {
            return builder.In(expr, values);
        }

        var filters = values
            .Select(v => builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i")));

        return builder.Or(filters);
    }
}

然后您可以简单地:

var filter = Builders<Companies>.Filter.In(c => c.Name, companyNames, true);
var result = _collection.Find(filter).ToList();