Contents

Laravel中使用MongoDB

扩展

查询

我要查所有images包含uurl的数据

https://static.duan1v.top/images/10861128-61202d548f798d73.webp
  • 原生sql
1
db.getCollection('shops').find({'images':{"$elemMatch":{'uurl':{$exists:r=true}}}})
  • 使用laravel可以写成
1
2
3
4
5
6
7
8
9
$a = Shop::query()
    ->where('images', '=', [
        '$elemMatch' => [
            'uurl' => [
                '$exists' => ['r' => true]
            ]
        ]
    ])->get();
dd($a);
  • toSql得到
1
select * from "shops" where "images" = ? and "deleted_at" is null and "meta"."status" != ?
  • 若使用下面的方式只能得到images中的子数组均含有uurl的记录
1
2
3
4
5
6
Shop::query()
    ->where('images', '<>', [])
    ->whereNotNull('images')
    ->where('images.uurl', '<>', [])
    ->whereNotNull('images.uurl')
    ->get();
coffee