MongoDB.NET Driver failing to create nested documents 3 levels deep

1 week ago 12
ARTICLE AD BOX

I've been unable to create MongoDB documents nested to a third level, using the .NET driver for MongoDB. The top-level class has a list of the second-level objects. The second-level class has a list of third-level objects. However, the insert operation fails to include the third-level doc data. The project is a console application using MongDB.Driver v3.7.

I also tried to manually register the third-level Doc definition, but that code may be incorrect. However, is it necessary to register all documents, below the second level for the driver, to "detect" it?

Class definitions for documents:

public class LibraryUser { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } = ObjectId.GenerateNewId().ToString(); public required int UserId { get; set; } public List<Book> Books { get; set; } = []; public void AddBook(Book book) { Books.Add(book); } } public class Book { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } = ObjectId.GenerateNewId().ToString(); public string BookTitle { get; set; } public int Price { get; set; } List<Review> Reviewers { get; set; } = []; public void addReview(Review review) { Reviewers.Add(review); } } public class Review { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } = ObjectId.GenerateNewId().ToString(); public string Reviewer { get; set; } public int Grade { get; set; } }

Code to create a nested document:

iMongoDatabase.CreateCollection("LibraryUsers"); LibraryUsersCollection = iMongoDatabase!.GetCollection<LibraryUser>("LibraryUsers"); LibraryUser userDoc = new() // First Level { UserId = 999999 }; Book book = new() // Second Level { BookTitle = "Old Yeller", Price = 11 }; Review review = new() // Third Level { Reviewer = "Corin", Grade = 55 }; book.addReview(review); // Add Review doc to Book userDoc.AddBook(book); // Add Book doc to LibraryUser doc LibraryUsersCollection.InsertOne(userDoc);

Code for registering Review class - which did not help.

MongoDB.Bson.Serialization.BsonClassMap.RegisterClassMap<Review>(classmap => { classmap.AutoMap(); classmap.MapMember(p => p.Reviewer); classmap.MapMember(p => p.Grade); });

Resultant data viewed with Mongosh:

db.LibraryUsers.find() [ { _id: ObjectId('69e22dcac06b765666fcda19'), UserId: 999999, Books: [ { _id: ObjectId('69e22dcac06b765666fcda1a'), BookTitle: 'Old Yeller', Price: 11 } ] } ]

GitHub repo

Read Entire Article