skip to Main Content

I am using this package for my Laravel Application. I can get single collection data using this query:

$product = DB::connection( 'mongodb' )->collection( 'products_1' )->paginate( 5 );

Now, I have multiple collection for e.g:

products_2, products_3, products_4 and so on…

I want to get data from all the collection at once.

Could you tell me is there any way I can get ?

Thank You.

2

Answers


  1. I feel the best way to go about this is to define the model for the collection having in mind that relational db uses tables while non-relational db like mongo uses collections, ill suggest you define your mongo collection in a model class.

    Just like a normal model, the MongoDB model class will know which collection to use based on the model name. For Products, the collection Products will be used.

    use JenssegersMongodbEloquentModel;
    
    class Book extends Model
    {
        protected $collection = 'products';
    }
    
    Login or Signup to reply.
  2. First, create a Product model:

    use JenssegersMongodbEloquentModel;
    
    class Product extends Model
    {
        protected $collection = 'products_1';
    }
    

    Then try to use $unionWith aggregation in whereRaw function:

    $products = Product::whereRaw(function($collection) {
        return $collection->aggregate([
            [
                '$unionWith' => [
                    'coll' => 'products_2',
                ]
            ],
            [
                '$unionWith' => [
                    'coll' => 'products_3',
                ]
            ],
            [
                '$unionWith' => [
                    'coll' => 'products_4',
                ]
            ],
        ]);
    })->paginate(5);
    

    Ref:

    If not work, try raw with toQuery:

    $products = Product::raw(function($collection) {
        return $collection->aggregate([
            [
                '$unionWith' => [
                    'coll' => 'products_2',
                ]
            ],
            [
                '$unionWith' => [
                    'coll' => 'products_3',
                ]
            ],
            [
                '$unionWith' => [
                    'coll' => 'products_4',
                ]
            ],
        ]);
    })->toQuery()->paginate(5);
    

    Ref: https://github.com/jenssegers/laravel-mongodb/issues/1574

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search