Create Index using Moloquent with Laravel

5.2k views Asked by At

I am new to MongoDB.

I am using Jensegger/Laravel-MongoDB Moloquent features to work on Mongo DB.

I am trying to create an index of a collection in this method:-

Schema::collection('events', function ($table) {
     $table->index(['location' => '2dsphere']);
});

However, I am getting error:-

Class Jenssegers\Mongodb\Schema' not found

I have added these two as well:-

use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

I have a controller method which is given below:-

public function fetchMongoTest(Request $request){
    $error = FALSE;
    $respond = array();
    $detail = array();
    $err_message = array();
    $err_validation = array();
    $api_code       = 2001; 
    try 
    {
        if ($request->isMethod('post')) 
        {
            $latitude = (float)$request->latitude;
            $longitude = (float)$request->longitude;
            $status     = 1;
            $mongoData = array();
            $monTestObj = new Mongotest;

            Schema::collection('events', function ($table) {
                $table->index(['location' => '2dsphere']);
            });

            $monTestObj->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0]];
            $monTestObj->save();



            $users = MongoTest::where('loc', 'near', [
                '$geometry' => [
                    'type' => 'Point',
                    'coordinates' => [
                        $longitude,
                        $latitude
                    ]
                ],
                '$maxDistance' => 10,
            ]);

            foreach($users as $u)
                {
                    print_r($u->name);
                }


        }
        else 
        {
            $status     = 0;
            $message    = Config::get('customConfig.api_messages.ENG.post_request_mandatory');
            $err_message[] = $message;
        }
    }
    catch(Exception $e) 
    {
        $status = 0; 
        echo $e->getMessage(); die;
        $message=Config::get('customConfig.api_messages.ENG.exception_error');
    }
    $response['status']         = $status;
    $response['message']        = $message;
    $response['details']        = $detail;
    $response['error']          = $err_message;
    $response['error_validation_key'] = $err_validation;
    $response['api_version']    = $this->api_version;
    $response['api_code']       = $api_code;

    $respond['fetch-activity-list-prime'] = $response;
    $jsonResult = json_encode($respond);    
    header('Content-Type: application/json; charset=utf-8');    
    echo $jsonResult ;      
    exit();
}

How can I check if a collection exists and if not, create a new collection?

EDIT:

This is my MongoTest model:-

<?php
namespace App\Http\Model;
//use Illuminate\Database\Eloquent\Model;
use Moloquent;
class MongoTest extends Moloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'test';
    //protected $collection = 'rh_country_help_text';
}
1

There are 1 answers

0
Neil Lunn On BEST ANSWER

You seems to have picked up a partial answer from somewhere. The Schema should be picked up from a "Larvel Migration", which is one recommended way of actually defining indexes in your application.

The process would be to set up like:

Create the Migration

php artisan make:migration create_location_index

Then alter the structure to add the up and down for create and drop of the index:

<?php

    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

    class CreateLocationIndex extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->index([ "loc" => "2dsphere" ]);
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->dropIndex(['loc_2dsphere']);
            });
        }
    }

Then you can run the migration as detailed within the documentation

If you decide to run the code outside of a migrations process then alternate handles for getting the MongoDB\Collection object can be like:

DB::collection('test')->raw(function($collection) {
  return $collection->createIndex([ 'loc' => '2dsphere' ])
}

Whatever you do though this code does not belong in the controller. The code to create an index need only be run once. Typically "once only" on your database deployment, but it does not really hurt to issue the command on every application start up, however it certainly hurts with every request. So just don't put it there.