Mongodb C#驱动程序执行字符串包含对嵌入文档中属性的查询

Mongodb C#驱动程序执行字符串包含对嵌入文档中属性的查询,c#,mongodb,mongodb-query,mongodb-.net-driver,C#,Mongodb,Mongodb Query,Mongodb .net Driver,我有以下简化模型: 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 {

我有以下简化模型:

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

}
但是,生成正确结果的手工查询如下所示:

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

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

将您的
where
子句更改为:

.Where(e=>e.Components.Any(c=>c.Value.ToLower().Contains(queryOptions.Filter)))
产生此聚合的:

db.Entity.aggregate([
{
“$match”:{
“Components.Value”:/green/is
}
}
])
下面是一个测试程序:

使用MongoDB.Entities;
使用MongoDB.Entities.Core;
使用System.Collections.Generic;
使用System.Linq;
命名空间堆栈溢出
{
公共类实体:实体
{
公共IList组件{get;set;}
}
公共类ComponentProperty
{
公共字符串PropertyName{get;set;}
公共字符串值{get;set;}
}
公共静态类程序
{
私有静态void Main()
{
新DB(“测试”);
新东方
{
组件=新列表{
新组件属性{
PropertyName=“测试”,
Value=“红色”}
}
}.Save();
新东方
{
组件=新列表{
新组件属性{
PropertyName=“测试”,
Value=“绿色”}
}
}.Save();
var result=DB.Queryable()
.Where(e=>e.Components.Any(c=>c.Value.ToLower().Contains(“绿色”))
.ToList();
}
}

}
我终于注意到,过滤器“绿色”实际上从浏览器中传递了一个引号,我真傻,竟然怀疑包含的内容是否以其他方式起作用。谢谢你的帮助,我得到了ref查询来验证我的
aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" : /^'green'$/i} } } }])
aggregate([{ "$match" : { "Components" : { "$elemMatch" : { "Value" :  {$regex: '.*green.*' } } } } }])