[CSHARP-2198] Update.Set Decimal Created: 19/Feb/18  Updated: 27/Oct/23  Resolved: 26/Nov/18

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

Type: Task Priority: Major - P3
Reporter: Oleg Temnov Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

.netcore 2, linux



 Description   

public Task SetPrice(Guid id, decimal price) {
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(Environment.GetEnvironmentVariable("DB")));
var mongoConnection = new MongoDB.Driver.MongoClient(settings);
var collection = mongoConnection.Database.GetCollection<BsonDocument>("test");
return collection.UpdateOneAsync(Builders<BsonDocument>.Filter.Eq("_id", id), Builders<BsonDocument>.Update.Set("price", price), new UpdateOptions {IsUpsert = true});
}

as a result, I get

{ "_id" : NUUID("ecefa3d7-8553-446a-ac46-6f565d05d33a"), *"price" : "22.3"* }

But I expect to get

{ "_id" : NUUID("ecefa3d7-8553-446a-ac46-6f565d05d33a"), "price" : *NumberDecimal("22.3")* }

 Comments   
Comment by Robert Stam [ 26/Nov/18 ]

The default serializer for values of type System.Decimal is a DecimalSerializer, and the default representation for a DecimalSerializer is a string. This is for historical reasons, as the BsonDecimal128 type was not added until more recently.

If you want the driver to write the System.Decimal value as a BsonDecimal128 use a cast to let the driver know that:

Builders<BsonDocument>.Update.Set("price", (BsonDecimal128)price)

Comment by Oleg Temnov [ 20/Feb/18 ]

So, the reason is that UpdateDefinition uses DecimalSerializer to write decimal. But BsonValue always converts decimal to BsonDecimal128.

Should UpdateDefinition behave same as BsonValue?

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