我有两个集合可以用这些类建模(简化版本(:
public class Profile
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid? Id { get; set; }
public string Name { get; set; }
[BsonRepresentation(BsonType.String)]
public Guid UserId { get; set; }
}
public class User
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid? Id { get; set; }
public string UserName { get; set; }
public bool IsConfirmed { get; set; }
}
我需要一个查询来获取其User
具有IsConfirmed
标志等于 true 的所有UserProfiles
,然后我需要过滤掉其 Id 包含在排除 ID 列表中的那些:
IList<Guid> profileIdsToExclude
这是我到目前为止构建的查询:
var professionalProfilesQuery =
(from profileCollection in _mongoContext.Database.GetCollection<Profile>("profiles").AsQueryable()
join userCollection in _mongoContext.Database.GetCollection<User>("users").AsQueryable()
on profileCollection.UserId equals userCollection.Id.Value
into users
orderby profileCollection.Name
select new ProfessionalProfile
{
Id = profileCollection.Id,
Name = profileCollection.Name,
UserId = profileCollection.UserId,
IsConfirmed = users.First().IsConfirmed,
})
.Where(p => p.IsConfirmed && !profileIdsToExclude.Contains(p.Id.Value));
其中ProfessionalProfile
是返回查询结果的类:
public class ProfessionalProfile
{
public Guid? Id { get; set; }
public string Name { get; set; }
public Guid UserId { get; set; }
public bool IsConfirmed { get; set; }
}
我得到用户配置文件,只有那些带有IsConfirmed
的配置文件等于真。但是,其 Id 在排除的 Id 列表中不会过滤掉,而是由查询返回的。
知道我想做的事情是否可行以及如何做吗?
提前谢谢。
您在这里的问题是由一点类型混淆引起的。
驱动程序创建的查询在末尾包含一个$match
阶段,如下所示:
{
$match: {
IsConfirmed: true,
Id: {
$nin: [ BinData(3, "DBA38D51FC28094BA2D6439E95643A49") ]
}
}
}
因此,它实际上是在尝试排除具有具有特定 Guid 值的字段的结果。但是,您正在存储 Guid 的字符串,以便筛选器不会排除任何内容。为了解决这个问题,您可以执行以下操作:
改变
.Where(p => p.IsConfirmed && !profileIdsToExclude.Contains(p.Id.Value));
到
.Where(p => p.IsConfirmed && !profileIdsToExclude.Contains(p.Id));
和
IList<Guid> profileIdsToExclude
到
IList<Guid?> profileIdsToExclude