【问题标题】:C# and MongoDB - Returning values from an objectC# 和 MongoDB - 从对象返回值
【发布时间】: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();
   }

请有人帮我找到解决方案或指出正确的方向。

【问题讨论】:

标签: c# mongodb blazor


【解决方案1】:

有了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();
}

上面的语句返回用户的所有数据以及报表上的详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2021-08-09
    相关资源
    最近更新 更多