Home > Enterprise >  Increment all fields of a MongoDB document from c#
Increment all fields of a MongoDB document from c#

Time:01-20

I have this c# object:

public class Stats
{
      [BsonElement("Miss")]
      public uint Miss { get; set; }

      [BsonElement("Success")]
      public uint Success { get; set; }

      [BsonElement("Failed")]
      public uint Failed { get; set; }
}

and the mongodb doc

{
      "_id": {
            "$oid": "63c5f18ea66843e308557658"
      },
      "PlayerId": 10000,
      "Miss": 10,
      "Success": 20,
      "Failed": 5
}

For now to incremnt all I use this:

var filter = Builders<BsonDocument>.Filter.Eq("PlayerId", playerId);
var update = new BsonDocument("$inc", new BsonDocument {
      { "Miss", Stats.Miss },
      { "Success", Stats.Success },
      { "Failed", Stats.Failed }
  });
var doc = Collection.FindOneAndUpdateAsync(filter, update).Result;

Is there any other way simplified, as the actual doc has many more fields ?

Mention: PlayerId field to be excluded. I can also move it to _id if it is easier. All the remaining fields are int.

Thank you.

CodePudding user response:

As you have constructed the class just for the properties to be updated, you could use .ToBsonDocument() to convert an object to BsonDocument which is simpler than working with System.Reflection.

BsonDocument updateFields = stats.ToBsonDocument();

var update = new BsonDocument("$inc", updateFields);

Demo

enter image description here

  • Related