Back

Update Individual Fields in Mongo

How to update specific fields in the MongoDB for a document or set of documents.

When using the Save method of a DataServer for a given type the entire document is serialized and updated on the server. This is accetable for the majority of cases for NetCanvas Applications.

However, there are situations where you need to ensure the update command is as efficient as possible. For example if you wanted to track the number of views / clicks & when the last view / click occoured, it's better to use mongoDB's server opperations. Here's How.

Using Inc to increase the value of a field

So lets track the number of views a document has had, assuming the document has a property nViews the following C# will locate the document and increase (Inc / $inc) the value by the given amount.

Import the right namespace

You need to reference some namespaces from the MongoDB assembly, to use some of the Classes & Methods /Extension Methods below.

using MongoDB.Driver;
using MongoDB.Driver.Builders;

The FindAndModifyArgs property

The FindAndModify method now recivies a FindAndModifyArgs object, which contains all the details needed to match the required document(s) and update the given properties.

// Define the Find & Mod Args
var args = new FindAndModifyArgs(){

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

  // Define the Update Command
  Update =  Update
    .Inc("nViews", 1)  // Increase the nViews property by 1
};

Execute FindAndModify

Once you have your args defined you can now execute the update on the given colletion / DataBase :

// Gather the collection to be updated
var coll = GeneralApp.DB.WebPages
  .mongoCollection;

// Execute the Find & Mod
coll.FindAndModify(
  args
);

Demo $inc number of nViews

Checkout the demo of the above example

Using Set

Using Inc is great for simple increments / decrements but what about setting an explicit value?

Well it's exactlly the same except you use the Set method of the Update command and pass the explicit value.

// The new value
var val = 0;

// Define the Find & Mod Args
var args = new FindAndModifyArgs(){

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

  // Define the Update Command
  Update =  Update
    .Set("nViews", val) // Set the nViews to the new value
};

Demo $set number of nViews

Checkout the demo of the above example

Speed

These updates are really fast. The average time taken to POST the request to the server, execute the update on the DB & re-render the HTML response in the browser is ~40ms. Take in to account Network latency & the normal HTTP request overhead shows just how fast these update are.