-
-
Save jamesikanos/b5897b1693b5c3dd1f87 to your computer and use it in GitHub Desktop.
public static class MongoClientExtensions | |
{ | |
/// <summary> | |
/// Evaluates the specified javascript within a MongoDb database | |
/// </summary> | |
/// <param name="database">MongoDb Database to execute the javascript</param> | |
/// <param name="javascript">Javascript to execute</param> | |
/// <returns>A BsonValue result</returns> | |
public static async Task<BsonValue> EvalAsync(this IMongoDatabase database, string javascript) | |
{ | |
var client = database.Client as MongoClient; | |
if (client == null) | |
throw new ArgumentException("Client is not a MongoClient"); | |
var function = new BsonJavaScript(javascript); | |
var op = new EvalOperation(database.DatabaseNamespace, function, null); | |
using (var writeBinding = new WritableServerBinding(client.Cluster, new CoreSessionHandle(NoCoreSession.Instance))) | |
{ | |
return await op.ExecuteAsync(writeBinding, CancellationToken.None); | |
} | |
} | |
} |
Seems that with latest Mongo Driver 2.5.0 the new WritableServerBinding constructor requires ICoreSessionHandle parameter, which can't be null.
This worked for me.
In 2.5 that using statement can be re-written:
var writeBinding = new WritableServerBinding(client.Cluster, new CoreSessionHandle(NoCoreSession.Instance);
This worked for me.
In 2.5 that using statement can be re-written:
var writeBinding = new WritableServerBinding(client.Cluster, new CoreSessionHandle(NoCoreSession.Instance);
Updated with suggestion, thank you.
This piece of code doesn't work anymore with MongoDB 4.0.0+, $eval
was dropped.
This piece of code doesn't work anymore with MongoDB 4.0.0+,
$eval
was dropped.
Thanks, @TomyCesaille. It was good while it lasted.
This piece of code doesn't work anymore with MongoDB 4.0.0+,
$eval
was dropped.
See https://www.mongodb.com/blog/post/going-in-mongodb-42#:~:text=Eval%20has%20left%20the%20building&text=What's%20changed%20in%20MongoDB%204.2,all%20operations%20on%20the%20database..Thanks, @TomyCesaille. It was good while it lasted.
Are you aware of a possible alternative to this ?
Would like to run a command like so:
db.loadServerScripts();
addFunction(1,2); // -> 3
where addFunction is defined like so:
// to add a function
db.system.js.insertOne(
{
_id : "addFunction" ,
value : function (x, y){ return x + y; }
}
);
Does the c# driver support multi line statements ?
Using the new C# MongoDb driver there is no 'easy' mechanism to execute JavaScript on the MongoDb server.
Simple extension method provided above. Import into your project and just call:
await Database.EvalAsync("return 'From Javascript';");