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
{
[BsonId]
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);
collection.InsertOne(record);
}
public void UpsertRecord<T>(string table, Guid id, T record)
{
var collection = db.GetCollection<T>(table);
var result = collection.ReplaceOne(
new BsonDocument("_id", id),
record,
new ReplaceOptions { IsUpsert = true });
}
}
//Program.cs
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 = "Charity@iamtimcorey.com"});
user.EmailAddresses.Add(new EmailAddressModel(){ EmailAddress = "bi1qqqg@me.com"});
db.UpsertRecord(tableName, user.Id, user);