[CSHARP-1243] Set Value to a BsonElement Created: 20/Apr/15  Updated: 05/Apr/19  Resolved: 27/Apr/15

Status: Closed
Project: C# Driver
Component/s: BSON, Documentation, Serialization
Affects Version/s: 2.0
Fix Version/s: None

Type: Task Priority: Blocker - P1
Reporter: petrica [X] Assignee: Unassigned
Resolution: Done Votes: 0
Labels: driver, question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:
  • VS 2013
  • NET Frameworks 4.5.1
  • Windows 8.1 x64


 Description   

Hi,
I want to set a value to a bson element in C# driver 2.0, in last version 1.9.2 this code works ok:
date.Value = BsonValue.Create(date.Value.ToUniversalTime().ToString("o"));
but in the new version 2.0, Value only have get and i don't find how to set the value.



 Comments   
Comment by Robert Stam [ 20/Apr/15 ]

In the 2.0 version of the driver the BsonElement class was changed to an immutable struct. The two primary reasons this was done were:

1. Performance, structs create less pressure on the garbage collector
2. Immutability, less chance of unintended side effects when an existing BsonElement is mutated

You can probably change your code to just replace the value of your date variable with an entire new BsonElement instance:

date = new BsonElement(date.Name, date.Value.ToUniversalTime().ToString("o"));

Although depending on where the value of your date variable came from you might have been depending on mutating the existing instance.

For example, the following code will no longer behave the same as it did in 1.10:

var date = document.GetElement("date");
date = new BsonElement(date.Name, date.Value.ToUniversalTime().ToString("o"));

In 2.0 this code only modifies the date variable, leaving the original document unchanged. If your intent is to update the "date" field inside a document write this instead:

document["date"] = document["date"].ToUniversalTime().ToString("o");

Comment by Craig Wilson [ 20/Apr/15 ]

Hi Petrica,

Questions like this are better asked in our public forums: https://groups.google.com/forum/?pli=1#!forum/mongodb-csharp or on stackoverflow. However, since we are here...

To answer this question, we need a bit more information. What is the type of your "date" variable?

Craig

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