我在我的symfony项目中使用MongoDB。为了与数据库进行通信,我正在使用文档管理器和MongoClient。
我打算做的是将数组直接批量插入数据库。我已经尝试创建数组并填充它。但是当我执行批处理插入((时,我得到这个异常
[MongoException]
no documents given
非常令人困惑,因为根据手册,如果插入的数组为空,则会引发异常。我已经确保并尝试了很多次,我插入的数组不是空的。这是我的代码:
$dm = $this->getContainer()->get('doctrine_mongodb');
echo "initiating... 'n";
$data = $dm->getRepository("KahviDocumentBundle:Suppliers")->findAll();
$children = array();
echo "fetched'n";
echo "'n".count($data)."'n";
$items = array();
foreach ($data as $row) {
foreach ($row->getValue()->getConsigneeName() as $consignee) {
$items[] = array(
'id' => Util'Util::slugify($consignee),
'name' => $consignee,
'data' => array(
'band' => $row->getValue()->getShipperName(),
'relation' => 'Buyer of band'
)
);
}
// echo $row->getValue()->getShipperName()."'n";
}
echo "items collected'n".count($items)."'n";
foreach ($items as &$item) {
$parent = $item['data'];
$children[Util'Util::slugify($parent['band'])][] = &$item;
}
unset($item);
foreach ($items as &$item) {
if (isset($children[$item['id']])) {
$item['children'] = $children[$item['id']];
}
}
unset($item);
// die();
echo "start deleting'n";
$mongo = new 'MongoClient('mongodb://192.168.125.17:27017');
$db = $mongo->selectDB('dbname');
// print_r($db);
$collection = $db->the_collection;
// print_r($collection);
$response = $collection->drop();
echo "finished'n";
print_r($response);
// die();
echo "starting recording'n";
$newCollection = $db->createCollection(
"the_collection",
array(
'capped' => true,
'size' => 1024*1024,
'max' => 10
)
);
echo "children count ".count($children)."'n";
$trees = array();
foreach ($children as $key => $child) {
$test = array(
'id' => $key,
'name' => $key,
'children' => is_array($child) ? $child : array()
);
$serialized = serialize($test);
$trees[] = $serialized;
// echo $serialized."'n";
}
// die();
var_dump($trees);
$newCollection->batchInsert($trees);
// $dm->getManager()->flush();
echo "finished'n";
您已经插入了一个字符串数组,而预期的类型是一个数组的数组,其中内部数组是一组列(字段(而且,您不需要重新创建已删除的相同集合。
所以应该是这样的。
$db = $mongo->selectDB('dbname');
$collection = $db->the_collection;
$collection->drop();
$trees = array();
foreach ($children as $key => $child) {
$test = array(
'id' => $key,
'name' => $key,
'children' => is_array($child) ? $child : array()
);
// echo print_r($test);
// echo "'n";
$serialized = serialize($test);
$trees[] = array('column1' => $serialized, 'column2'=> $key);
}
$collection->batchInsert($trees);