[英]C# and MongoDB - Returning values from an object
我希望有人可以提供帮助:
我有一个用户的 MongoDB 集合,它有一个名为 Reports 的数组,其中包含具有 ID 的对象。 我可以检索 ID,但我正在尝试从另一个集合中检索查找值,因此 User.Reports.Id 应该返回与 Reports 集合中该 ID 关联的值。 这类似于 Mongoose 中的 .populate 函数。
我尝试了许多解决方案,但似乎无法使其正常工作。 根据我的研究,似乎我应该使用 aggregate().lookup() 但我还没有设法让它工作。
public class UserModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
//from azure active directory b2c
public string? ObjectIdentifier { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? DisplayName { get; set; }
public string? EmailAddress { get; set; }
public string? PhoneNumber { get; set; }
public List<BasicReportsModel> Reports { get; set; } = new();
}
public class BasicReportsModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public BasicReportsModel()
{
}
public BasicReportsModel(ReportsModel report)
{
Id = report.Id;
}
}
private readonly IMongoCollection<UserModel> _users;
private readonly IMongoCollection<ReportsModel> _reports;
public MongoUserData(IDbConnection db)
{
_users = db.UserCollection;
_reports = db.ReportsCollection;
}
public async Task<UserModel> GetUserData(string id)
{
// this brings back the user model with the Reports array and objects. I need to bring back the documents related to the ID's in User.Reports.Id
var results = await _users.FindAsync(u => u.Id == id);
return results.FirstOrDefault();
}
请有人帮我找到解决方案或指出正确的方向。
使用aggregate
和$lookup
,您就走在了正确的轨道上。 为了让它与 C# 驱动程序一起工作,您应该定义一个包含报告的模型类,例如:
public class UserWithReportsModel : UserModel
{
public IEnumerable<ReportsModel> Reports { get; set; }
}
然后,您可以更改您的GetUserData
方法以使用$lookup
阶段执行聚合:
public async Task<UserWithReportsModel> GetUserData(string id)
{
return await (_users.Aggregate()
.Match(x => x.Id == 1)
.Lookup(foreignCollection: _reports,
localField: x => x.ReportIds,
foreignField: x => x.Id,
@as: (UserWithReportsModel x) => x.Reports))
.FirstOrDefaultAsync();
}
上述语句返回用户的所有数据以及报告的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.