通过C#驱动程序执行mongodb shell脚本 [英] Execute mongodb shell script via C# driver

查看:304
本文介绍了通过C#驱动程序执行mongodb shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了这个问题,但并没有理解.是否可以通过C#驱动程序执行任意的mongodb shell脚本?

I have read this question and haven't understand. Is there ability 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");
}

此代码更改了someProperty的类型,该类型是集合的集合的元素:

This code changes type of someProperty which is element of a collection of a collection:

some_items mongo collection:

{
   some_collection: [{ someProperty: 12, ....}],
   ....

}

这篇关于通过C#驱动程序执行mongodb shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆