Reputation: 4232
I am using laravel-mongodb
(https://github.com/jenssegers/laravel-mongodb) to manipulate mongodb data.
How to create a new MongoDB collection with laravel-mongodb?
for example:
public function test()
{
$newArtciels = DB::connection('mongodb')->collection('articles')->where('status', '1')->get();
//I want to ceate a new collection `new_artciels`, and save `$newArtciels` into `new_artciels`,how to write next?
}
Question:
I want to ceate a new collection new_artciels
, and save $newArtciels
into new_artciels
,what should I do?
Upvotes: 0
Views: 3685
Reputation: 81
You don't need to create collect in first time. when insert first data in mongo collection, it just create and store data according to your data.
In laravel framework best way use jenssegers
package. U can find it documentation from here.
It so easy to use. just add mongo db connection to config like bellow
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'options' => [
'appname' => 'homestead',
],
],
After that extend your model from jenssegers model like bellow
use Jenssegers\Mongodb\Eloquent\Model;
class Book extends Model
{
protected $collection = 'books';
protected $connection = 'mongodb';
}
And finally create(or save if exists collection) like bellow:
$book = new Book();
$book->title = 'A Game of Thrones';
$book->save();
It so Easy!!!!! Enjoy :)
Upvotes: 0
Reputation: 583
Hey you can use this to crate collections
DB::connection('mongodb')->createCollection("logger");
Refer document : https://www.php.net/manual/en/mongodb.createcollection.php
Upvotes: 1
Reputation: 305
Model
<?php
namespace App;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class new_artciels extends Eloquent
{
protected $collection = 'new_artciels';}
Controller
use App\new_artciels;
this should work for you.
Upvotes: 1