Begayim Muratalina
Begayim Muratalina

Reputation: 661

mongodb: insert mysql columns as a mongodb sub-documents

i'm trying to import mysql table to mongodb collection. i want to put mysql columns as mongodb sub-documents: MYSQL =>

| col1 | col2 | col3 | col4 |
------------------------------
| abc  | def  | ghi  | jkl  |
------------------------------
| 1234 | 5678 | 9876 | 4567 |
------------------------------
| abc  | def  | ghi  | jkl  |
------------------------------
etc.....

In mongodb want them to look like : MongoDB =>

> doc1: { 
>                col1["abc", "1234", "abc", .....],
>                col2["def", "5678", "def", .....],
>                col3["ghi", "9876", "ghi", .....],
>                col4["jkl", "4567", "jkl", .....],
>                etc.

i use php and my code looks like this :

$sql=mysql_query("select * from mytable") or die (mysql_error());
$count=mysql_num_rows($sql);
if (count > 0) {
while($data=mysql_fetch_row($sql)){
$mosql[]=$data;
}
$collection -> insert($mosql)
}

as the output I got this, it gives me rows not columns:

doc1: { col1:[0:"abc", 1:"def", 2:"ghi", 3:"jkl".....], col2:[0:"1234", 1:"5678", 2:"9876", 3:"4567" .....], col3:[0:"abc", 1:"def", 2:"ghi", 3:"jkl".....], etc.

Does someone knows what i'm doing wrong? Thanks for any help!

Upvotes: 0

Views: 302

Answers (2)

Begayim Muratalina
Begayim Muratalina

Reputation: 661

Finally i figured out how to do this, may be this way is too long but i got what i want:

//var77
foreach( $mytables as $table => $struct ) {
  $sql77 = mysql_query("SELECT WINDSHEAR FROM XL_10331_EXPLOIT_251012 where flightid like '191622'") or die( mysql_error() );
  $count77 = mysql_num_rows( $sql77 );
  // If it has content insert all content
  if( $count77 > 0 ) {
    while($info77 = mysql_fetch_row($sql77)) {
      $mosql77[]=$info77[0];
  }

//var78
foreach( $mytables as $table => $struct ) {
  $sql78 = mysql_query("SELECT WING_AI_SYS_ON FROM XL_10331_EXPLOIT_251012 where flightid like '191622'") or die( mysql_error() );
  $count78 = mysql_num_rows( $sql78 );
  // If it has content insert all content
  if( $count78 > 0 ) {
    while($info78 = mysql_fetch_row($sql78)) {
      $mosql78[]=$info78[0];
  }

      $collection->insert(array('flightid'=>191622, 'AI_PB_ON_1'=>$mosql77, 'AI_PB_ON_2'=>$mosql78, etc....)); 

Upvotes: 1

Amith Koujalgi
Amith Koujalgi

Reputation: 10952

You may want to try looping through the array of rows returned from MySQL and inserting documents into MongoDB collection one after the other, rather than inserting the whole array at once.

Upvotes: 1

Related Questions