【问题标题】:mongodb: insert mysql columns as a mongodb sub-documentsmongodb:将 mysql 列插入为 mongodb 子文档
【发布时间】:2013-02-13 09:57:24
【问题描述】:

我正在尝试将 mysql 表导入 mongodb 集合。我想将 mysql 列作为 mongodb 子文档: MYSQL =>

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

在 mongodb 中希望它们看起来像: MongoDB =>

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

我使用 php,我的代码如下所示:

$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)
}

作为我得到的输出,它给了我行而不是列:

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".....], 等等

有人知道我做错了什么吗? 谢谢你的帮助!

【问题讨论】:

  • 您所看到的部分内容,01 等,作为字段,通常发生在 MongoDB 驱动程序遇到看起来/行为像数组的东西时, '不是平台/语言中的本机数组。
  • 我已经编辑了我的问题,我犯了一个错误,实际上我的数据看起来像这样 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".....]等

标签: php mysql mongodb


【解决方案1】:

最后我想出了如何做到这一点,可能是这种方式太长了,但我得到了我想要的:

//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....)); 

【讨论】:

    【解决方案2】:

    您可能想尝试遍历从 MySQL 返回的行数组,并将文档一个接一个地插入 MongoDB 集合,而不是一次插入整个数组。

    【讨论】:

    • 这个我试过了,但是变量很多,表很多,我怕我一个一个做,会花很多时间跨度>
    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2016-04-14
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多