首页 > 解决方案 > Mongodb C# 驱动程序执行字符串包含对嵌入文档中的属性的查询

问题描述

我有以下简化模型:

public class Entity
{
    public Guid Id { get; set; }

    public IList<ComponentProperty> Components { get; private set; }

}

public class ComponentProperty
{
    public string PropertyName { get; set; }

    public string Value { get; set; }

}

我希望能够找到其属性值字符串包含搜索字符串的任何实体,为此我根据推荐here编写了以下查询,该查询隐式使用了正则表达式:

var query = _context.GetCollection<Entity>()
                        .AsQueryable()
                        .Where(t => t.Components.Any(c => c.Value.ToLower() == queryOptions.Filter));

此查询生成以下 json,并且(错误地)返回 0 行:

aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" : /^'green'$/i} } } }])

但是,产生正确结果的手工查询如下:

aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" :  {$regex: '.*green.*' } } } } }])

也许,我在使用 c# 驱动程序的方法中忽略了一些东西,任何指针都将不胜感激。

标签: c#mongodbmongodb-querymongodb-.net-driver

解决方案


将您的where条款更改为:

.Where(e => e.Components.Any(c => c.Value.ToLower().Contains(queryOptions.Filter)))

产生这种聚合:

db.Entity.aggregate([
    {
        "$match": {
            "Components.Value": /green/is
        }
    }
])

这是一个测试程序:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Collections.Generic;
using System.Linq;

namespace StackOverFlow
{
    public class Ntity : Entity
    {
        public IList<ComponentProperty> Components { get; set; }
    }

    public class ComponentProperty
    {
        public string PropertyName { get; set; }

        public string Value { get; set; }

    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the RED color" }
                }
            }.Save();

            new Ntity
            {
                Components = new List<ComponentProperty> {
                    new ComponentProperty {
                        PropertyName = "test",
                        Value = "the Green color" }
                }
            }.Save();

            var result = DB.Queryable<Ntity>()
                           .Where(e => e.Components.Any(c => c.Value.ToLower().Contains("green")))
                           .ToList();
        }
    }
}


推荐阅读