1

I have some data that saved in MongoDB,I want to transfer them to MySQL.

I use MongoDB PHP Library to do this,and I write a demo for test below:

MongoDB PHP Library docs:
https://docs.mongodb.com/php-library/master/
http://php.net/manual/en/book.mongodb.php

TestController.php

   //insert some test data into mongodb
   public function insertMongodb()
    {
        $collection = (new \MongoDB\Client)->test->articles;

        $collection->insertMany([
            ['title' => 'hello', 'content' => 'hello...'],
            ['title' => 'foo', 'content' => 'foo...'],
            ['title' => 'bar', 'content' => 'bar...'],
        ]);
        dd('ok');
    }



    //query the data from mongodb and insert them into mysql
    public function queryAndInsertMysql()
    {
        $collection = (new \MongoDB\Client)->test->articles;

        $cursor = $collection->find();

        //how to write next?

    }

In mysql,there is a table articles,it has these fields:

id
title
content

I want to transfer the query result from mongodb into mysql table articles.

Question:
In the second function queryAndInsertMysql(),how to insert the result that queried form mongodb into mysql?

zwl1619
  • 4,002
  • 14
  • 54
  • 110

1 Answers1

2

It looks like you are a little confused about how to insert records in Laravel. You are calling the insertMany() method on a Collection.

I would suggest setting up 2 database connections in your application, 1 for the MongoDB and 1 for the MySQL.

See this question and answer for help on creating multiple database connections in Laravel How to use multiple database in Laravel

Then pull from one database and insert into another:

$articles = DB::connection('mongodb')->table('articles')->get();

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

If this is a one-off task it should possibly be part of a migration not a controller.

Martin Joiner
  • 3,529
  • 2
  • 23
  • 49
  • Thanks!There is another question when running the code,see my update. – zwl1619 Sep 04 '17 at 09:50
  • 1
    You've edited your original question so it now includes my answer but with a new additional question. This is very confusing for future readers and StackOverflow advises against asking multiple questions in the same post. Consider moving this problem to a new question and keeping the original question and answer as a consistent pair. – Martin Joiner Sep 04 '17 at 09:55