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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!There is another question when running the code,see my update.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.