You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel-MongoDB查询含非空images字段的MongoDB记录

解决方案

针对你的需求,有几种更可靠的方式来构建查询,避开$expr可能带来的兼容性问题:

方法一:直接排除空数组

利用MongoDB对空数组的原生判断,结合exists条件,代码简洁且高效:

$advertisements = Advertisement::query()
    ->where('status', Advertisement::ACTIVE)
    ->where('images', 'exists', true)
    ->where('images', '!=', []);

也可以使用MongoDB原生操作符$ne实现同样效果:

$advertisements = Advertisement::query()
    ->where('status', Advertisement::ACTIVE)
    ->where('images', 'exists', true)
    ->where('images', '$ne', []);

方法二:明确检查数组长度大于0

如果需要精准判断数组元素数量,可直接使用$size结合$gt的原生查询逻辑,无需包裹$expr:

$advertisements = Advertisement::query()
    ->where('status', Advertisement::ACTIVE)
    ->where('images', 'exists', true)
    ->whereRaw(['$gt' => [['$size' => '$images'], 0]]);

原代码失效原因

部分版本的laravel-mongodb包对$expr的解析支持不够完善,直接传递MongoDB原生操作符数组给whereRaw,能绕过ORM层的解析问题,查询稳定性更高。

内容的提问来源于stack exchange,提问作者Hossein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:58:11