c# - 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# 驱动程序的方法中忽略了一些东西,任何指针都将不胜感激。
解决方案
将您的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();
}
}
}
推荐阅读
- r - 如何按血统获取彼此相关的值索引列表?[R]
- python - 无法使用机器人框架(Python)单击 div 内的链接
- ios - 几何阅读器的两种实现,但一种不工作
- python - Docker Traefik 无法路由 websocket
- azure-active-directory - OpenId Connect 身份验证和 Azure AD 范围混淆
- c++ - 为什么不将具有默认参数的函数传递给模板化构造函数并使用 lambda 将其存储为 std::function
工作? - python - 更新 4.2.1 后 Spyder 无法加载
- android - 为什么我在使用音频播放器时出错:^0.17.3 包,错误是“任务':app:processDebugManifest'的执行失败,构建失败”
- python - 带有关键字和提交事务
- google-apps-script - 为什么 Google 表格或 Google 应用程序脚本没有为我提供与显示的时间值相同的时间值?