c# - C# MongoDB 加入集合并包含过滤器
问题描述
开始使用 MongoDB.Driver 在我的 .net 核心应用程序中使用 MongoDB。我需要找到一种方法来加入集合并包含过滤器。
寻找如何加入这是我发现的 -
var query = from c in collection1.AsQueryable()
join m in collection2.AsQueryable() on
c.ClassTwoId equals m.Id into j
select new { c, j };
寻找如何过滤这是我发现的 -
//filters
FilterDefinitionBuilder<PortalUser> builder = Builders<PortalUser>.Filter;
List<FilterDefinition<PortalUser>> filters = new List<FilterDefinition<PortalUser>>();
filters.Add(builder.Eq(PortalUser => PortalUser.IsActive, true));
var result = portalUserCollection.FindAsync<PortalUser>(builder.And(filters));
找不到任何方法来组合上面的示例......我发现过滤 IQueryable 的唯一方法是在 IQueryable 中添加 where 语句,但由于过滤器是动态的并且决定运行时,这意味着我必须这样做很多 if/else 并每次都重建 IQueryable,这听起来很疯狂......
有人知道解决方法吗?
非常感谢。
解决方案
使用 Where 子句。
var query = from c in collection1.AsQueryable().Where(x => x.Name == "Test")
join m in collection2.AsQueryable() on
c.ClassTwoId equals m.Id into j
select new { c, j };
通过添加 nuget 包 System.Linq.Dynamic 使其动态化
using System.Linq.Dynamic;
....
var query = from c in collection1.AsQueryable().Where("Age == 123")
join m in collection2.AsQueryable() on
c.ClassTwoId equals m.Id into j
select new { c, j };
有关动态查询的更多信息,请参阅 System.Linq.Dynamic(参数等)上的文档
推荐阅读
- c# - prestashop 将类别树重新生成到 c#
- parrot-os - Parrot OS 卡住了
- vue.js - 服务工作者缓存与 VuexPersistence
- node.js - 反应表 - 多个值到单元格
- sql - Oracle SQL 空行顺序
- unity3d - UNITY - 鼠标旋转播放器在 Unity 编辑器中完全免费,但在 webGL 构建中,鼠标仅旋转到屏幕边缘
- python - 使用修剪模型 Tensorflow 获得更快的推理?
- reactjs - products.map 不是函数
- ios - SwiftUI OAuth2.0 redirectURI 回调问题
- git - git lfs 不工作 - 仍然抛出错误 - 远程:错误:GH001:检测到大文件