Skip to content

MongoDB

在 Laravel 中使用

使用包 jenssegers/laravel-mongodb,用这个演示数据

json
{
    "id": "ex",
    "name": "example",
    "attributes": [
        {
            "name": "color",
            "value": "red"
        },
        {
            "name": "size",
            "value": 8
        },
        {
            "name": "style",
            "value": "old school"
        }
    ],
    "pets": [
        {
            "name": "dog",
            "toys": [
                {
                    "name": "disc",
                    "items": [
                        {
                            "brand": "a",
                            "color": "red"
                        },
                        {
                            "brand": "b",
                            "color": "blue"
                        }
                    ]
                },
                {
                    "name": "ball",
                    "color": "red"
                }
            ]
        },
        {
            "name": "cat",
            "toys": [
                {
                    "name": "feather",
                    "color": "white"
                }
            ]
        }
    ]
}

size 改为 9

php
$m = ExampleModel::where('id', 'ex')->first();
$m->where('attributes.size', 8)->update(['attribtues.$.size' => 9]);

深层更改

php
ExampleModel::raw()->updateOne([
    'id' => 'ex'
], [
    '$set' => [
        'pets.$[pet].toys.$[toy].items.$[item].color' => 'yellow'
    ]
], [
    'arrayFilters' => [
        ['pet.name' => 'dog'],
        ['toy.name' => 'disc'],
        ['item.brand' => 'b']
    ]
])

彩雲博客