【发布时间】:2022-06-14 19:17:40
【问题描述】:
希望有人能帮忙:
我有一个用户的 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();
}
请有人帮我找到解决方案或指出正确的方向。
【问题讨论】:
-
this 有用吗?