I have a base class Entity that has a string Id member and a derived class A.
But when creating a new instance of the derived class and using InsertOneAsync to add it to my collection, the document is added to the database with null as the Id value.
Using an ObjectId as the Id does seem to work, but I'm trying to prevent MongoDB dependency in my models.
I also experimented with the following code, but the results are the same:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});
Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record.
Indeed, it's not possible to store null values in a MongoDB document using a DataFrame. The Python None values are considered as missing attributes accordingly to this NoSQL specific allowance. However, if your column is numerical, you can force writing a null value by setting it to NaN.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
I had the same issue and finally got it to work (with the 2.0 driver) with these attributes:
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]
Or the equivalent BsonClassMap fluent interface:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id)
.SetSerializer(new StringSerializer(BsonType.ObjectId))
.SetIgnoreIfDefault(true);
});
I tried to get the same working with .ReplaceOneAsync with Upsert on but that always leaves the id still null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With