我使用MongoCollection :: batchInsert()将csv数据插入mongodb,
<?php
$mongo = new Mongo("mongodb://192.168.1.7:27017");
$collection = $mongo->test->cartoons;
$row = 1;
$handle = fopen(dirname(Yii::app()->request->scriptFile).'/images/importcsv/upload.csv', "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
$users = array();
for ($c=0; $c < $num; $c++) {
echo 'data--'.$data[$c] . "<br />\n";
}
$users[] =$data;
var_dump($users);
$collection->batchInsert($users);
}
?>
上面的代码将Mongo Collections中的数据作为两个单独的数组插入标题(CSV标题),另一个数据用于数据。
现在我想将CSV标头与数据合并,如下所示,以便在mongo中导入,
{ "_id" : ObjectId("52c10f355b9e5cf00200014d"), "Name" : "Dhanam R.", "DOB" : "12-Aug-80", "Age" : "80" }
答案 0 :(得分:2)
真的这个问题可以使用一些谷歌搜索,但这次只是,你做的是采取CSV的第一行:
$columns = fgetcsv($fh, 0, ',');
$nrColumns = count($columns);
for ($i=0; $i < $nrColumns; $i++)
{
if(array_key_exists($columns[$i], $columnsArray)){
$columnsArray[$columns[$i].$col_inc] = $i;
$col_inc++;
}else{
$columnsArray[$columns[$i]] = $i;
}
}
并使用它与$c
中的指数进行比较:
$user = array();
for ($c=0; $c < $num; $c++) {
$user[$columnsArray[$c]] = $data[$c]
echo 'data--'.$data[$c] . "<br />\n";
}
然后使用$user
添加到数组中:
$users[] =$user;
答案 1 :(得分:0)
create CSV file in Mongo Db using php code given below:-
<?php
set_time_limit(0);
ob_start();
// connect to mongodb
$mongo = "172.00.22.00:27017";
$conn = new MongoClient("mongodb://$mongo");
if (!$conn) {
die("Unable to connect with mongodb");
}
$db = $conn->nexg_tmp;
//header('Content-Type: application/csv');
//header('Content-Disposition: attachment; filename=example.csv');
//header('Pragma: no-cache');
//$regex = new MongoRegex("/^LIV/");
//$where = array('code' => $regex);
$col1 = $db->ASSETS;
$col2 = $db->BITFRAME;
//$records = $col1->find($where)->limit(5);
//$records = $col1->find()->limit(1500);
$records = $col1->find();
//$records = $col1->find(array('code' => 'LIV002'))->limit(5);
$csvarr = array();
$fp = fopen('example.csv', 'w');
$headings[] = "Code";
$headings[] = "CH/VOD CODE";
$headings[] = "CH/VOD NAME";
$headings[] = "VOD/LIVE";
$headings[] = "URL1";
$headings[] = "URL2";
fputcsv($fp, $headings);
foreach ($records as $val) {
$csvarr = array();
$csvarr['code'] = $val['code'];
$csvarr['charge_code'] = $val['charge_code'];
if (empty($val['name'])) {
$val['name'] = $val['channel_name'];
}
/* if(empty($val['type'])){
$val['type'] ="VOD";
} */
$csvarr['name'] = @$val['name'];
$csvarr['type'] = @$val['type'];
$rec_BitFrameCol = $col2->find(array('code' => $val['code'], 'type' => $val['type']));
foreach ($rec_BitFrameCol as $k => $BitFrameval) {
$csvarr['url' . $k] = $BitFrameval['url'];
}
fputcsv($fp, $csvarr);
}
echo "Completed Successfully..";
?>