我有以下简化的模型:
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编写了以下查询,该查询隐式使用了Regex:
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#驱动程序的过程中,我忽略了一些东西,任何指针将不胜感激。
将您的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();
}
}
}