Search code examples
mongodbyii2yii2-active-records

MongoDB string field value length in Yii2


I just read How to query the string field value length in MongoDB and successfully got a query working when used directly in MongoDB console. The query I used was:

db.getCollection('language').find({
  name: {$ne: ''}, 
  $where: "this.i18n.length < 3"
})

I am now trying to duplicate the same in Yii2:

$languages = Language::find()
  ->where(['$ne', 'name', ''])
  ->andWhere(['<', 'this.i18n.length', '3'])
  ->all();

but the array is empty.

I have tried the query without string length:

$languages = Language::find()
  ->where(['$ne', 'name', ''])
  ->all();

and the array is populated.

I have also tried the query with string length alone:

$languages1 = Language::find()
  ->where(['<', 'this.i18n.length', '3'])
  ->all();
$languages2 = Language::find()
  ->where(['<', 'i18n.length', '3'])
  ->all();

but array remains empty.

Question is: How do I get $where: "this.i18n.length < 3" to work in Yii2?


Solution

  • I guess there's no way to query the db directly. I have instead filtered the results in php:

    $languages = Language::find()->where(['$ne', 'name', ''])->all();
    foreach ($languages as $fac) {
      if(strlen($fac->i18n)<3){
        // my code here
      }
    }
    

    Thanks.