开发者

Execute mongodb shell script via C# driver

I have read this question and haven't understand. Is there abili开发者_Python百科ty to execute arbitrary mongodb shell script via C# driver?


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, ....}],
   ....

}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜