How to insert parent and child data like sql server or any difference?

[BsonCollection(“Student”)]
public class Student
{
public ObjectId Id {get;set;}
public string StudentId { get; set; }
public IList Courses{get;set;}
}
[BsonCollection(“Course”)]
public class Course
{
public ObjectId Id {get;set;}
public string CourseName{get; set;}
}

public async Task<CosResourceResponse> InsertAsync(Student entity)
{
try
{
await _unitOfWork.Compounds.InsertOneAsync(entity);

            return new CosResourceResponse<Student>(entity);
        }
        catch (Exception ex)
        {
            var message = $"An error occurred when insert the Person: {ex.Message}";
            _logger.Error(message, ex);
            return new CosResourceResponse<Student>(message);
        }
    }

How i will make primary key and foreignkey between these table so pls give example through c# into the mongod databse code and how to insert into the database

Hi, @murugan_m,

Welcome to the MongoDB Community Forums. I see that you are trying to model parent-child relationships with MongoDB. I would recommend reading our data modelling guide, especially the section Model Tree Structures for examples of how to design your object model.

Depending on your needs, you may wish to model your parent-child relationship using nesting in which case the primary/foreign key is implied through the nesting. If you do decide to model the parent-child relationship using separate collections for the parent and child objects, you can simply create new ObjectId values client-side using ObjectId.GenerateNewId() and wire together the relationships yourself. The driver does the same thing when you try to insert a new object and the _id field has a default value. It generates a new _id using the configured IIdGenerator and then performs the insert with the client-side generated _id.

Sincerely,
James

Hi James,

      Thanks for your reply can you please give me any sample code for that to continue. I am inserting student collection inside courses as a list in mongodb it's like embedded but i need to store separately to see student data and courses data.

Thanks & Regards
Murugansilvers

Hi, @murugan_m,

I’m glad that you found my response helpful. The code required will be highly dependent on which solution you choose to pursue and the structure of your persistence code.

If you wish to keep separate parent-child collections, then your persistence code would have to generate the ObjectIds and assign them to the appropriate properties on the parent and child objects. If you choose to nest the child objects as subdocuments, then the driver should take care of the serialization automatically.

Sincerely,
James