Search code examples
c#mongodbmongodb-querymongodb-.net-drivermongodb-csharp-2.0

how to update mongo db all records in c#


I have mongo db collection which stores the JSON. By mistakenly, one element value was updated wrong in all records of a collection.

How i will update the particular element ?

My json is like

{
status:
   {
     name:"john",
     value: "12345678903333.444"
   }
}

here the value property value should be long field, value will be replaced by

{
status:
   {
     "name":"john",
     "value": 1234567890
  }
} 

value should be trimmed as first 10 character of existing value.

After updating(from @mickl answer), different format - other than numeric

Converting to Int also got error! Screen


Solution

  • You can use $substr operator with $toDouble to convert string to number and then redirect aggregation results into the same collection using $out (which will basically update all its documents), Try in Mongo shell:

    db.col.aggregate([
        {
            $addFields: {
                "status.value": { $toDouble: { $substr: [ "$status.value", 0, 10 ] } }
            }
        },
        {
            $out: "col"
        }
    ])
    

    Or in C# code:

    var addFieldsBody = "{ $addFields: { \"status.value\": { $toDouble: { $substr: [ \"$status.value\", 0, 10 ] } } } }";
    
    Col.Aggregate()
       .AppendStage<BsonDocument>(BsonDocument.Parse(addFieldsBody))
       .Out("col");