首页 > 解决方案 > 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,这听起来很疯狂......

有人知道解决方法吗?

非常感谢。

标签: c#mongodbjoin.net-corenosql

解决方案


使用 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(参数等)上的文档


推荐阅读