'C# and MongoDB - Returning values from an object

I'm hoping someone can help:

I have MongoDB collection for a User which has an Array called Reports which holds objects with IDs. I can retrieve the IDs but I'm trying to retrieve the lookup values from another collection, so the User.Reports.Id should return the values associated with that ID in the Reports collection. This would be something similar to the .populate function in Mongoose.

I have tried a number of solutions but don't seem to be able to get it working. From my research, it seems I should be using aggregate().lookup() but I haven't managed to get it working.

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

Please could someone help me find a solution or point me in the right direction.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source