使用php连接mongo db的字段

时间:2016-03-08 13:12:09

标签: php mongodb

我正在尝试使用php连接mongo db中的两个字段来处理庞大的数据集。下面是我到目前为止找到并尝试过的示例解决方案,但这在php中不起作用。如果有以下代码,任何人都可以帮助进行必要的更正。

var pipeline = [
        {
           "$project": {
            "data1": 1,
            "data2": { $concat: [ "$data1", " ", "$data2" ] }
            }
        }
],
cursor = db.collection.aggregate(pipeline),
bulkUpdateOps = cursor.map(function (doc) { 
    return { 
            "updateOne": {
                "filter": { "_id": doc._id },
                "update": { "$set": { "data2": doc.data2 } } 
             }
          };
});         
db.collection.bulkWrite(bulkUpdateOps);

我正在使用composer命令在评论中建议安装mongo-php-library:

$composer require "mongodb/mongodb=^1.0.0" 

但它没有用。 php mongo驱动程序是1.6.12。和mongo db版本是3.2.3。错误如下:

 Your version of PHP, 5.4.16, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.
  ./composer.json has been created
 Loading composer repositories with package information
 Updating dependencies (including require-dev)
 Your requirements could not be resolved to an installable set of packages.

  Problem 1

     - mongodb/mongodb 1.0.1 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system.

     - mongodb/mongodb 1.0.0 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system.

- Installation request for mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1].
  To enable extensions, verify that they are enabled in those .ini files:

- /etc/php.ini

- /etc/php.d/curl.ini

- /etc/php.d/dom.ini

- /etc/php.d/fileinfo.ini

- /etc/php.d/json.ini

- /etc/php.d/mbstring.ini

- /etc/php.d/mysql.ini

- /etc/php.d/mysqli.ini

- /etc/php.d/pdo.ini

- /etc/php.d/pdo_mysql.ini

- /etc/php.d/pdo_sqlite.ini

- /etc/php.d/phar.ini

- /etc/php.d/posix.ini

- /etc/php.d/sqlite3.ini

- /etc/php.d/sysvmsg.ini

- /etc/php.d/sysvsem.ini

- /etc/php.d/sysvshm.ini

- /etc/php.d/wddx.ini

- /etc/php.d/xmlreader.ini

- /etc/php.d/xmlwriter.ini

- /etc/php.d/xsl.ini

- /etc/php.d/zip.ini

  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

   Installation failed, deleting ./composer.json.

我需要帮助才能安装此库。我安装了错误的版本吗?

2 个答案:

答案 0 :(得分:5)

谢谢大家的帮助,但是我无法安装mongo php库,所以上面的解决方案对我没用。我找到了另一种方法,我想分享两个使用shell命令的字段。 在php文件中:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected WebView mWebView;
    protected InterstitialAd mInterstitialAd;

    protected int pageId = R.id.nav_home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initToolbar();
        //initDrawer();
        //initNavigationView();

        initAdInterstitial();

        if (savedInstanceState != null) {
            return;
        }

        initWebView();
        navigate();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        pageId = item.getItemId();
        navigate();
        return true;
    }

    protected void navigate() {

        // Close drawer if it is open.
        if(mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);
        }

        if(pageId == R.id.nav_home) {
            mWebView.loadUrl(URL_INDEX);
        }
        else if(pageId == R.id.nav_level0) {
            mWebView.loadUrl(getLevelUrl(0));
        }
        else if(pageId == R.id.nav_level1) {
            mWebView.loadUrl(getLevelUrl(1));
        }
        else if(pageId == R.id.nav_level2) {
            mWebView.loadUrl(getLevelUrl(2));
        }
        else if(pageId == R.id.nav_level3) {
            mWebView.loadUrl(getLevelUrl(3));
        }
        else if(pageId == R.id.nav_history) {
            mWebView.loadUrl(URL_LAST_PLAYED);
        }
    }

    protected void initWebView() {

        mWebView = (WebView) findViewById(R.id.webview);

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        // Deprecated.
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            Context c = mWebView.getContext();
            webSettings.setDatabasePath(c.getFilesDir().getPath() + c.getPackageName() +
                    "/databases/");
        }

        mWebView.setWebViewClient(new WebViewClient() {

            /*
             * HERE IS WHERE THE INTERSTITIAL AD IS SHOWN.
             *
             * Shows the interstitial ad every n-th page load.
             */
            public void onPageFinished(WebView view, String url) {

                // After WebView page is loaded:

                // Update page load count.
                navigationCount = (navigationCount + 1) % adFrequency;

                // Show ad once every n-th page load.
                if(navigationCount == 0) {
                    showAd();
                }
            }
        });
    }

    protected void initAdInterstitial() {
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });
        requestNewInterstitial();
    }

    protected void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(adRequest);
    }

    public void showAd() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }
}

concat.sql

$concat_Command = "mongo < concat.sql";
shell_exec($concat_Command);

答案 1 :(得分:2)

如果没有看到您尝试在PHP中解决此问题,以下大部分内容都基于假设,因此可能无法提供最佳解决方案,但仍然可以作为指导您朝着正确的方向发展的方向 解决你的问题。

将PHP驱动程序与免费的 mongo-php-library 一起使用,该驱动程序在裸机驱动程序之上实现功能更全面的API,构建聚合管道和随后的批量更新操作为:

$pipeline = [["$project" => ["data1" => 1, "data2" => ["$concat" => [ "$data1", " ", "$data2" ]]]]];
$operation = new Aggregate($databaseName, $collectionName, $pipeline, ['typeMap' => $typeMap]);
$cursor = $operation->execute($primaryServer);
$results = iterator_to_array($cursor);

function mapper($doc) {
    return [
        "updateOne" => [
            ["_id" => $doc["_id"]], 
            [
                "$set" => [
                    "data2" => $doc["_id"]
                ]
            ]
        ]
    ]
};

$ops = array_map("mapper", $results);
$bulkUpdateOps = new BulkWrite($databaseName, $collectionName, $ops);
$writeResult = $bulkUpdateOps->execute($primaryServer);

在上文中,$primaryServerBulkWrite execute()方法的参数,该方法应包含MongoDB\Driver\Server对象的实例,即您的主要MongoDB服务器连接详细信息。 $typeMap变量是Aggregate()构造函数中的可选参数,用于表示BSON反序列化的类型映射。这将应用于返回的光标。

如果您正在使用旧版驱动程序,请考虑运行以下操作,该操作使用MongoDB提供的Bulk Operations API&gt; = 2.6&lt; = 3.0:

$client = new MongoClient();
$collection = $client->selectCollection("database", "collection");

$pipeline = array(         
    array(
        "$project" => array(
            'data1' => 1,
            "data2" => array("$concat" => array( "$data1", " ", "$data2" ))
        )
    )
);

$batch = new MongoUpdateBatch($collection);
$counter = 0;

foreach ($collection->aggregate($pipeline) as $doc ) {
    $batch->add(
        array(
            "q" => array( '_id' => $doc['_id'] ),
            "u" => array( 
                '$set' => array(
                    "data2" => $doc["data2"]
                )
            )
        )
    );
    $counter++;

    if ($counter % 500 === 0) {
        $retval = $batch->execute(array( 'w' => 1));
        $counter++;
        $batch = new MongoUpdateBatch($collection);        
    }
}

if ($counter > 0) {
    $retval = $batch->execute(array( 'w' => 1 ));
}