Home > Net >  whereBetween doesn't work in laravel mongodb
whereBetween doesn't work in laravel mongodb

Time:07-07

Hello I'm new in MongoDB laravel and I have the following error:

This is the object I want to query in Mongo.

MongoDB Compass

I want to fetch timestamps that are greater than or equal to 2022/7/5 and less than or equal to 2022/7/6, according to my logic in Laravel with the Jenssegers/laravel-mongodb, would have this:

$tracks =  TrackFishing::where('boat_id', '3')
    ->whereBetween(
         'tracking.timestamp', array(
             Carbon::createFromDate(2022, 7, 5),
             Carbon::createFromDate(2022, 7, 6)
         ))
    ->first();

I want to get position 0 of the timestamp but this throws me empty, I'd appreciate your help

CodePudding user response:

You need to specify the hour, minute and second

$tracks =  TrackFishing::where('boat_id', '3')
    ->whereBetween(
         'tracking.timestamp', array(
             Carbon::createFromDate(2022, 7, 5)->startOfDay(),
             Carbon::createFromDate(2022, 7, 6)->endOfDay()
         ))
    ->first();

CodePudding user response:

The mongodb way of doing it is using $gte(greater than or equal), $gt(greater than) and $lte(less than or equal), $lt(less than) and $eq for equal.

Check Comparison Query Operators for reference

$condition['boat_id']['$eq'] = '3';
$condition['tracking.timestamp']['$gte'] = Carbon::createFromDate(2022, 7, 5)->startOfDay();
$condition['tracking.timestamp']['$lt'] = Carbon::createFromDate(2022, 7, 6)->endOfDay();

TrackFishing::where($condition)->first();

Note: you can also write inside the where I just wrote it in a variable to keep it clean.

CodePudding user response:

I solved with a aggregate:

$cursor = Model::raw()->aggregate([
        ['$match' => [
                'tracking.timestamp' => [
                    '$gte' => new \MongoDB\BSON\UTCDateTime(Carbon::createFromFormat("Y-m-d", $request->fecha_inicio)->startOfDay()),
                    '$lte' => new \MongoDB\BSON\UTCDateTime(Carbon::createFromFormat("Y-m-d", $request->fecha_fin)->endOfDay())
                ],
            ]
        ],
    ]);

this question helped me

thank you all for replying

CodePudding user response:

try with this one;

    'tracking.timestamp', [
        Carbon::createFromDate(2022, 7, 5),
        Carbon::createFromDate(2022, 7, 6)
    ]
  • Related