Yii2转换MongoDB文本查询时出现类型错误:TypeError strtoupper(): Argument #1 ($string) must be of type string, array given
解决Yii2 MongoDB文本查询中的TypeError错误
问题背景
我在MongoDB终端中执行文本索引创建及查询命令都能正常运行,且支持排序:
db.stores.createIndex( { name: "text", description: "text" } ) db.articles.find( { $text: { $search: "coffee" } } )
随后我在Yii2框架中编写了如下查询代码(参考MongoDB文本查询语法):
$collection = Yii::$app->mongodb->getCollection('mydata'); $result = $collection->find([ [ '$text' => [ '$search' => $key, ] ] ]);
但运行代码时出现错误:TypeError strtoupper(): Argument #1 ($string) must be of type string, array given,请求协助解决。
错误原因
你在find()方法里多嵌套了一层数组!Yii2的MongoDB组件要求查询条件是单层关联数组,而你把$text的条件包在了一个外层数组中,导致Yii2内部试图把这个外层数组当作字段名去执行strtoupper()操作,自然就抛出了类型错误。
解决方案
去掉多余的外层数组,直接将文本查询条件作为find()的参数:
$collection = Yii::$app->mongodb->getCollection('mydata'); // 修正后的查询代码 $result = $collection->find([ '$text' => [ '$search' => $key ] ]);
扩展:添加排序支持
如果需要像终端里那样支持排序(比如按文本匹配得分排序),可以在find()后链式调用sort()方法:
$result = $collection->find([ '$text' => [ '$search' => $key ] ])->sort([ '$score' => -1 // 按匹配得分降序排列 ]);
这样修改后,你的查询就能正常执行,同时支持文本搜索和排序功能了。
内容的提问来源于stack exchange,提问作者im-learning
相关产品推荐
相关产品推荐

