Upsert Not Creating Unique GUID

TLDR: The same _id is always used when using collection.ReplaceOne on a newly instantiated object.

Every time I try to Upsert a new unique record using collection.ReplaceOne , it just overwrites my previous record. As you can see in the screenshot the _Id for the Upsert is AAAAAAAAAAAAAAAAAA== . I’m not sure what is happening. I would like to be able to insert/update in 1 action.

When using InsertOne they are created in the database with a unique Guid.

This is my first experience with MongoDB so I’m not sure where I’m going wrong. I have been following a tutorial and my code is the same as the tutorials, however I’m having issues.

public class ContactModel
    public Guid Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<EmailAddressModel> EmailAddresses { get; set; } = new();
    public List<PhoneNumberModel> PhoneNumbers { get; set; } = new();
public class MongoDBDataAccess
    private static IMongoDatabase db;
    static string tableName = "Contacts";

    public void InsertRecord<T>(string table, T record)
        var collection = db.GetCollection<T>(table);

    public void UpsertRecord<T>(string table, Guid id, T record)
        var collection = db.GetCollection<T>(table);
        var result = collection.ReplaceOne(
            new BsonDocument("_id", id),
            new ReplaceOptions { IsUpsert = true });

MongoDBDataAccess db = new("MongoContactsDB", GetConnectionString());
string tableName = "Contacts";

ContactModel user = new() { FirstName = "Ceehaoi", LastName = "Corey" };
user.PhoneNumbers.Add(new PhoneNumberModel(){ PhoneNumber = "552115-555-5555"});
user.PhoneNumbers.Add(new PhoneNumberModel(){ PhoneNumber = "91wqqe239123"});
user.EmailAddresses.Add(new EmailAddressModel(){ EmailAddress = ""});
user.EmailAddresses.Add(new EmailAddressModel(){ EmailAddress = ""});

db.UpsertRecord(tableName, user.Id, user);

You’re not setting a value for GUID or rather the an implicit empty Guid has been created, all 0’s

A new Guid would have to be instantiated when you create the user object.

Thanks for the reply! Shouldn’t the database automatically generate the new guid so there are no duplicates? Like I said, my collection.InsertOne(record) is creating a Guid automatically.

I’m not sure the correct way to implement this and any insight you have would be greatly appreciated.