I have read this question and haven't understand. Is there ability to execute arbitrary mongodb shell script via C# driver?
3 Answers
var mongoServer = MongoServer.Create("mongodb://<connectionstring>");
var database = mongoServer.GetDatabase("mydatabase");
string mycollectionCount database.Eval("function() { return db.mycollection.count(); }").ToString();
This is useful when you are trying to change property types for example like this:
string updateScript = @"
function () {
db.some_items.find().forEach(function(documentItem) {
documentItem.some_collection.forEach(function(collectionItem) {
if (typeof collectionItem.SomeProperty === 'number'
&& Math.floor(collectionItem.someProperty) === collectionItem.someProperty)
{
collectionItem.someProperty = '' + collectionItem.someProperty;
}
});
db.modules_elementary.save(documentItem);
});
return true;
}";
var updateResult = MongoReadDatabase.Database.Eval(updateScript).ToString();
if (updateResult != "true")
{
throw new ApplicationException("Update of something failed");
}
This code changes type of someProperty which is element of a collection of a collection:
some_items mongo collection:
{
some_collection: [{ someProperty: 12, ....}],
....
}
3 Comments
Database.Eval() method returns BsonValue - the result of script execution on server. You can try to cast it to some BsonDocument, taking into consideration, that script execution could be failed by server and instead some Data in BsonValue you will have error message in the Eval()'s result. Anyways, this all code is a hack. If you are using this code in a normal app execution flow, you are definitely doing something wrong.No, you'd need launch a Mongo shell process, using something like Process.Start, and pass in the command you want to execute, e.g.
mongo.exe mydb --eval "printjson(db.getCollectionNames())"
However, the C# driver can do most things the shell can, so if possible it's much easier to use the driver directly.
3 Comments
Process.Start and passing it command to execute. But it seems that it should work. It's a pity, that I cannot manage only with C# driver here. Using mongo admint util and Process.Start looks a bit clumsy. If nobody adds any new idea how to use only C# driver to run arbitrary mongo shell script in nearest time, I will accept this answer.new BsonDocument(...) nested into each other beyond the point of decency and sanity.I have not tried it but I think this is what you are looking for:
MongoServer.RunAdminCommand Method (String) http://api.mongodb.org/csharp/1.1/html/a83249ae-0989-7c24-7240-4506053d83c1.htm
3 Comments
server.RunAdminCommand(@"db.blog.insert({title: ""My Blog Post""});"); gives error Command 'db.blog.insert({title: "My Blog Post"});' failed: no such cmd: db.blog.insert({title: "My Blog Post"}); (response: { "errmsg" : "no such cmd: db.blog.insert({title: \"My Blog Post\"});", "bad cmd" : { "db.blog.insert({title: \"My Blog Post\"});" : true }, "ok" : 0 })MongoServer.RunAdminCommand() method.