Last active
January 28, 2022 04:26
-
-
Save jamesikanos/b5897b1693b5c3dd1f87 to your computer and use it in GitHub Desktop.
MongoClient C# Eval Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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 ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, @TomyCesaille. It was good while it lasted.