Laravel-mongodb: MongoDB specific operators :: $size

Created on 24 Jul 2019  路  11Comments  路  Source: jenssegers/laravel-mongodb

I am trying to find the mongo documents having a field with specific array size. As per the jessenger guide the code to find documents with a specific size is given:

User::where('tags', 'size', 3)->get();

But I need to find conditions like:
Greater than a value, Less than a value, Not Equal and Between.

Can anyone help me with this?

Most helpful comment

@Abhinanddas, you can do like this

$departmentId = 20;
$query = User::where('department_id', '=', 10);
if ($departmentId === 20) {
      $query->whereRaw(['$where' => 'this.scores.length > 1'])
} else {
     $query->whereRaw(['$where' => 'this.scores.length > 3'])
}
dd($query->get());

All 11 comments

@Abhinanddas, You should use aggregate function

User::raw(function ($collection) {
    return $collection->aggregate(
        [

            [
                '$project' => [
                    'size_of_tags' =>  ['$size' =>  '$tags']
                ]
            ],
            [
                '$match' => [
                    'size_of_tags' => [
                        '$gt' => 3
                    ]
                ]
            ]
        ]
    );
});

I am working with a dynamic where clause. So I need a way to find the value ranges in the eloquent model. Can't do it with the aggregate function.

You can use operator $where

Try use like this

Since I am working on a dynamic where clause, I cant use raw expressions.

What do you mean in dynamic where clause?

Let me show my code. I am working on Laravel.

$query= Collection_Model();
$query=$query->where('field_name',value);
if(condition){
$query=$query->where('field_name',value);
}else{
$query=$query->where('field_name',value);
}

Since I am building a Query based on various conditions and clauses, I can't use aggregation.

@Abhinanddas, you can do like this

$departmentId = 20;
$query = User::where('department_id', '=', 10);
if ($departmentId === 20) {
      $query->whereRaw(['$where' => 'this.scores.length > 1'])
} else {
     $query->whereRaw(['$where' => 'this.scores.length > 3'])
}
dd($query->get());

@Abhinanddas, do you solve your problem?

@Smolevich Thanks bro it worked......

@Abhinanddas, please close issue

Was this page helpful?
0 / 5 - 0 ratings

Related issues

phuocduy1988 picture phuocduy1988  路  3Comments

Vasiliy-Bondarenko picture Vasiliy-Bondarenko  路  3Comments

imrannazirbhat picture imrannazirbhat  路  3Comments

Idnan picture Idnan  路  3Comments

pirmax picture pirmax  路  3Comments