2017-09-04 66 views
0

我正在使用laravel-mongodbhttps://github.com/jenssegers/laravel-mongodb)来操作mongodb数据。如何从mongdoDB的查询结果中删除`_id`字段?

我想将数据传输到MySQL,从MongoDB的查询,还有一个演示功能,要做到这一点:

TestController.php

public function queryAndInsertMysql() 
{ 
    $articles = DB::connection('mongodb')->collection('articles')->get()->toArray(); 

    DB::connection('mysql')->table('articles')->insert($articles); 

    dd('ok'); 
} 

有这个函数运行时错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '_id' in 'field list' (SQL: insert into `articles` (`_id`, `content`, `title`) values (59ad186437dd1f1968004334, hello..., hello), (59ad186437dd1f1968004335, foo..., foo), (59ad186437dd1f1968004336, bar..., bar)) 

出现该错误是因为在mongodb集合中有_id字段,
并且有i s没有_id字段在mysql表中,
所以我需要删除_id字段,然后再将它们插入到mysql中。

我尝试用array_shift()做到这一点,但它不工作:

public function removeId() 
{ 
    $articles = DB::connection('mongodb')->collection('articles')->get()->toArray(); 

    foreach ($articles as $article) { 
     array_shift($article); 
    } 


    dd($articles); 
} 

_id领域仍然存在:

enter image description here

我该怎么办?

回答

1

您需要使用投影过滤_id出:

public function queryAndInsertMysql() 
{ 
    $articles = DB::connection('mongodb') 
     ->collection('articles') 
     ->project(['_id' => 0]) 
     ->get() 
     ->toArray(); 

    DB::connection('mysql')->table('articles')->insert($articles); 

    dd('ok'); 
} 

请注意,MongoDB是shemaless,除非你强制执行document validation,所以这将是明智的白名单,你希望插入SQL在project参数的所有字段:

public function queryAndInsertMysql() 
{ 
    $articles = DB::connection('mongodb') 
     ->collection('articles') 
     ->project(['_id' => 0, 'content' => 1, 'title' => 1]) 
     ->get() 
     ->toArray(); 

    DB::connection('mysql')->table('articles')->insert($articles); 

    dd('ok'); 
} 

这将保证即使你ACCI牙齿上有任何其他领域的文件,它将被忽略。

1

这是一个嵌套的数组,所以你需要使用扩展foreach循环,

foreach ($arr as $key => $value) { 
    /** Shift here... **/ 
} 

<?php 
$a = [ 
    0 => [ 
     '_id' => 'sdgsdg'  
    ] 
]; 

$y = ''; 

foreach ($a as $key => $val) { 
    $y = array_shift($a[$key]); 
} 

var_dump($y); /** ---> string(6) "sdgsdg" **/ 
?>