Auto Increment Function - How to call from C# Code while inserting a document?

As part of our project implementation, we are using Counters to auto increment certain fields of the collection as needed. We are using C# as programming language and using Mongo DB Native Drivers to connect to Mongo DB.

If I am using Mongo DB Command in Mongo Shell to insert a document which uses a function to auto increment a value, we run the below command. Here, you can see that we are calling the function.

db.student.insert({
  studentnum: getSequenceNextValue("studentnum"),
  student_id: "02940409",
  course: "Bachelor of Science in Computer Engineering",
  year_level: "2nd",
  department: "engineering"
});

getNextSequenceValue is a function which gives me the next counter value for use. But C# does not accept use of the function, instead, it expects a value.

var document = new BsonDocument { { “studentnum”, getSequenceNextValue(“studentnum”), }};

Is there a way in C# using Mongo DB Driver to achieve this? Or is there a way to run native Mongo DB Shell commands from C#?

Thanks,
Vikram

There is db.RunCommand discussed in https://stackoverflow.com/questions/38671771/run-mongodb-commands-from-c-sharp

You can use a JsonCommand like this:

var command = new JsonCommand<BsonDocument>("{ dropDatabase: 1 }");
db.RunCommand(command);

or use a CommandDocument like this:

var command = new CommandDocument("dropDatabase", 1);
db.RunCommand<BsonDocument>(command);

Unfortunately, it does not work that way. I have already looked at this post and tried it. It works for commands where there is no function involved. For example, if I try either of the below, it does not work and expects a JSON:

var stringCommand = "{\"_id\": getSequenceNextValue(\"itemId\"),\"student_id\": \"02740305\",\"course\": \"Bachelor of Science in Finance\",\"year_level\": \"2nd\",\"department\": \"Business Administration\"}";
            var command = new JsonCommand<BsonDocument>(stringCommand);
            database.RunCommand(command);
var stringCommand = "db.student.insert({\"_id\": getSequenceNextValue(\"itemId\"),\"student_id\": \"02740305\",\"course\": \"Bachelor of Science in Finance\",\"year_level\": \"2nd\",\"department\": \"Business Administration\"});";
            var command = new JsonCommand<BsonDocument>(stringCommand);
            database.RunCommand(command);

image

So, that Run Command does not run native Mongo Shell commands unfortunately.

Thanks.