使用PHP / Phalcon / MongoDB在新文档插入期间引用现有的ObjectId

时间:2015-10-21 11:11:37

标签: php mongodb phalcon

我使用以下代码使用robomongo客户端

将主要类别ID引用插入次要类别文档
@echo off
setlocal EnableDelayedExpansion

cd "C:\Files"
for %%a in (*.txt) do (

    REM Here's the problem...
    echo %%a

    set "str=%%a"
    set new_str=!str:0,3!
)

echo %new_string%

pause >nul

我在PHP风格中试过以下

    var parentDoc = db.getCollection('category').findOne({"slug":"Primary"});
    db.category.insert(
    {
        "name" : "Secondary",
        "slug" : "secondary",
        "taxonomy" : true,

        "ancestors" : [
        {
            "_id" : parentDoc._id,
            "name" : parentDoc.name
        }
        ]
    })

以Phalcon风格尝试

$query = '
    {
        "slug" : "fashion"
    }';
    $primaryCategory = Category::findFirst(array(json_decode($query,true))); //phalcon code
    $primary = array();
    $primary['_id'] = $primaryCategory->_id;
    $primary['name'] = $primaryCategory->name;

    $document = array(
            "name" => "Secondary2",
            "slug" => "secondary",
            "taxonomy" => true,
            "ancestors" => array($primary)
    );
    $category = $app->mongo->selectCollection('category');//phalcon style of fetching collection handle
    $category->insert($document);

    });

在上面的代码中,服务器和mongo之间有2次往返

  1. 获得parentDoc的第一个
  2. 第二个用于插入带有parentDoc引用标识的secondaryDoc
  3. 是否可以在1次往返中执行它们,我可以在secondaryDoc插入时引用parentDocId

1 个答案:

答案 0 :(得分:2)

您可以使用MongoDB 2.6或更高版本中提供的 Bulk API 来利用您的插入操作。当前的PHP驱动程序应该支持这些方法,特别是您需要 MongoWriteBatch 类来扩展 MongoInsertBatch 类以进行插入操作。实质上,该操作可以实现如下:

<?php
    $mc = new MongoClient("localhost");
    $collection = $mc->selectCollection("test", "category");

    $batch = new MongoInsertBatch($collection);
    $counter = 0;
    $query = array("slug" => "Primary");

    foreach ($collection->find($query) as $doc ) {

        $primary = array();
        $primary['_id'] = $doc->_id;
        $primary['name'] = $doc->name;

        $doc = array(
            "name" => "Secondary2",
            "slug" => "secondary",
            "taxonomy" => true,
            "ancestors" => array($primary)
        );
        $batch->add($doc);
        $counter++;

        if ( $counter % 1000 === 0 ) {
            $ret = $batch->execute(array("w" => 1));
            $counter++;
            $batch = new MongoInsertBatch($collection);        
        }
    }

    if ( $counter > 0 ) {
        $ret = $batch->execute(array("w" => 1));
    }
?>

在上文中,每个find()查询和插入操作都通过.add()方法添加到批处理中,以按顺序执行的顺序发送到服务器。因此,不是等待服务器对每个插入的写响应,而是分批发送和响应操作,因此往返的开销较少。