Reputation: 4232
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?
Upvotes: 1
Views: 863
Reputation: 3657
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.
Upvotes: 2