[CSHARP-1320] Empty _id using ReplaceOneAsync Created: 16/Jun/15  Updated: 05/Apr/19  Resolved: 27/Jan/16

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 2.0
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Ugo Lattanzi Assignee: Unassigned
Resolution: Done Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi,
running that code :

await this.Collection.ReplaceOneAsync(x => x.Name == city.Name x.CountryCode == city.CountryCode, newObject, new UpdateOptions()

{ IsUpsert = true }

);

if the object doesn't exist it create the new one but with an empty id.
Here what is stored

/* 1 */

{ "_id" : ObjectId("000000000000000000000000"), "CreateAt" : [ NumberLong(635700317931446025), 0 ], "UpdateAt" : [ NumberLong(635700317931446025), 0 ], "Name" : "My value", "CountryCode" : "it", "Culture" : "en-US" }

 Comments   
Comment by Craig Wilson [ 16/Jun/15 ]

Hi Ugo,

ObjectId is a value type (struct) and, as such, has a default value that is not null. Because of this, if you don't specify one, it gets pushed like that. ReplaceOneAsync is generally used when you know the _id of the object you are updating. In your case, that isn't true. The best thing to do will be to use the BsonIgnoreIfDefaultAttribute on the id property. This will prevent the id from getting written when it's null.

Craig

Generated at Wed Feb 07 21:39:16 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.