通过mongodb c#中另一个集合中的字段进行搜索



我一直在研究mongo的聚合和查找函数,以了解如何按不同集合中的字段进行搜索,但无法解决。

数据结构如下:

public class User
{ 
public string Id
public string Name
public string GroupId
}

public class Group
{
public string Id
public string Name
}

我试图在这里完成的是:返回一个组名为"的用户列表;xyz";。

下面是我返回的IExecutable,没有与组名称匹配的字段。

return userCollection.Aggregate(new AggregateOptions
{
Collation = new Collation("en",
strength: CollationStrength.Primary)
})
.Match(u=>u.Name.Contains("xyz")
.AsExecutable();

您可以使用$lookup阶段来实现这一点;此阶段在另一个集合中查找信息,并将匹配的文档添加到数组中以进行进一步处理。为了以类型安全的方式使用它,请创建一个具有组枚举的类,例如:

public class UserWithGroups : User
{
public IEnumerable<Group> Groups { get; set; }
}

此外,您需要为组创建一个集合,例如:

var grpCollection = db.GetCollection<Group>("groups");

然后你可以扩展你的声明如下:

return userCollection.Aggregate(new AggregateOptions
{
Collation = new Collation("en",
strength: CollationStrength.Primary)
})
.Match(u=>u.Name.Contains("xyz")
.Lookup<User, Group, UserWithGroups>(
grpCollection, 
x => x.GroupId, 
x => x.Id, 
x => x.Groups)
.Match(x => x.Groups.Any(y => y.Name.Contains("abc")))
.AsExecutable();

如果需要经常查询组名,也可以签出扩展引用模式并将组名存储在用户中。

最新更新