我在symfony项目中使用MongoDB。为了与数据库进行通信,我使用的是Document Manager和MongoClient。
我打算做的是将数组直接批量插入数据库。我已经尝试创建数组并填充它。但是当我执行batchInsert()时,我得到了这个异常
[MongoException]
no documents given
非常混乱,因为根据the manual,如果插入的数组为空,则抛出异常。我已经确定并且只是尝试了很多次我插入的数组不是空的。这是我的一段代码:
$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";
答案 0 :(得分:1)
您已经插入了一个字符串数组,而期望的类型是一个数组的数组,其中内部数组是一组列(字段) 而且,你不需要重新创建你放弃它的同一个集合。
所以它应该是这样的。
$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);