Update Individual MongoDB Document Fields

As distinct from writing the entire document to the DB


Demo $inc number of nViews

470

Return to the Associated Post for this example.

The Relevant C# to Increase a value

 // Wrap in to an Args
var args = new FindAndModifyArgs(){

  // Build the query to match the Document
  Query = Query.EQ(
    "_id",
    oWebPage.MongoId
  ),

  // Define the Update Command
  Update =  Update
    .Inc("nViews", 1),

};
  
// Execute the Find & Mod
GeneralApp.DB.WebPages
  .mongoCollection
  .FindAndModify(
    args
  );

Demo $set number of nViews

470

Return to the Associated Post for this example.

The Relevant C# to Explicity Define a value

// The new Value
var val = 0;
    
// Wrap in to an Args
var args = new FindAndModifyArgs(){

  // Build the query to match the Document
  Query = Query.EQ(
    "_id",
    oWebPage.MongoId
  ),

  // Define the Update Command
  Update =  Update
    .Set("nViews", val),

};
  
// Execute the Find & Mod
GeneralApp.DB.WebPages
  .mongoCollection
  .FindAndModify(
    args
  );