Hướng dẫn php update mongodb

Bài trước mình đã giới thiệu với mọi người cách thêm dữ liệu trong MongoDB bằng PHP rồi, bài này mình sẽ thực hiện sửa dữ liệu trong MongoDB bằng PHP.

1, Sửa một bản ghi.

Để sửa một bản ghi trong MongoDB các bạn sử dụng phương thức updateOne() với cú pháp như sau:

$collection->updateOne(filter, update, options);

Trong đó:

  • filter là mảng dữ liệu mà bạn muốn so khớp, lọc.
  • update là mảng dữ liệu mà bạn muốn thay thế cho dữ liệu được filter.
  • options là mảng chứa các thông số tùy chỉnh thêm.

Chú ý: Nếu như điều kiện filter trả về nhiều hơn một bản ghi thì dữ liệu chỉ được thay thế cho bản ghi đầu tiên.

VD: Mình sẽ thực hiện update lại thông tin cho Post có _id5a2b4f536e14730a780023f8.

tuts;

//selection collection
$post = $db->Post;

//update
$updatedResult = $post->updateOne(
    ['_id' => new MongoDB\BSON\ObjectId('5a2b4f536e14730a780023f8')],
    ['$set' => [
            'title'    => 'NewS Title',
            'content'  => 'new conten',
            'category' => 'Foo New',
        ],
    ]
);

//dump
var_dump($updatedResult);
die();

Phương thức update sẽ trả về đối tượng Update Result nếu thành công và sẽ trả về một error exception nếu thất bại.

object(MongoDB\UpdateResult)#16 (2) {
  ["writeResult":"MongoDB\UpdateResult":private]=>
  object(MongoDB\Driver\WriteResult)#15 (9) {
    ["nInserted"]=>
    int(0)
    ["nMatched"]=>
    int(1)
    ["nModified"]=>
    int(1)
    ["nRemoved"]=>
    int(0)
    ["nUpserted"]=>
    int(0)
    ["upsertedIds"]=>
    array(0) {
    }
    ["writeErrors"]=>
    array(0) {
    }
    ["writeConcernError"]=>
    NULL
    ["writeConcern"]=>
    object(MongoDB\Driver\WriteConcern)#14 (0) {
    }
  }
  ["isAcknowledged":"MongoDB\UpdateResult":private]=>
  bool(true)
}

2, Sửa nhiều bản ghi.

Tương tự như insert , đối với update. Khi bạn muốn update nhiều bản ghi thì bạn sẽ phải sử dụng phương thưc updateMany() với cú pháp tương tự như đối với updateOne().

VD: Mình sẽ sửa tất cả các Post có category Foo thành Bar.

tuts;

//selection collection
$post = $db->Post;

//update
$updatedResult = $post->updateMany(
    ['category' => 'Foo New'],
    ['$set' => [
            'category' => 'Bar',
        ],
    ]
);

//dump
var_dump($updatedResult);
die();

Và đây là kết quả mình nhận được khi dump.

object(MongoDB\UpdateResult)#15 (2) {
  ["writeResult":"MongoDB\UpdateResult":private]=>
  object(MongoDB\Driver\WriteResult)#14 (9) {
    ["nInserted"]=>
    int(0)
    ["nMatched"]=>
    int(3)
    ["nModified"]=>
    int(3)
    ["nRemoved"]=>
    int(0)
    ["nUpserted"]=>
    int(0)
    ["upsertedIds"]=>
    array(0) {
    }
    ["writeErrors"]=>
    array(0) {
    }
    ["writeConcernError"]=>
    NULL
    ["writeConcern"]=>
    object(MongoDB\Driver\WriteConcern)#13 (0) {
    }
  }
  ["isAcknowledged":"MongoDB\UpdateResult":private]=>
  bool(true)
}

3, Lời kết.

Phần này mình chỉ giới thiệu với mọi người cách update data trong MongoDB thôi, còn phần xử lý các dữ liệu trả về mình sẽ trình bày với mọi người vào một bài khác.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Bài Viết Mới

PHP là viết tắt của chữ "Hypertext Preprocessor", đây là một ngôn ngữ lập trình được sử dụng để viết ở phía máy chủ (server side). Và PHP là một open source, nên chính vì thế nó có tính cộng đồng của nó cao và đồng thời cũng sẽ có rất nhiều các framawork, CMS hỗ trợ như Laravel, Wordpress.

- MongoDB là một hệ quản trị cơ sở dữ liệu mã nguồn mở thuộc học NoSQL. Nó được thiết kế theo kiểu hướng đối tượng, các bảng trong MongoDB được cấu trúc rất linh hoạt, cho phép các dữ liệu lưu trữ trên bảng không cần tuân theo một cấu trúc nhất định nào cả (điều này rất thích hợp để làm big data).

Series này sẽ hướng dẫn mọi người cách Kết nối PHP đến MongoDB. Và đọc, ghi, sửa, xóa (CRUD) dữ liệu trên MongoDB sử dụng PHP.

Docs HomeMongoDB Manual


➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.


Note

Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the modifications to make instead of an update document. See the method reference page for details.

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.

Once set, you cannot update the value of the _id field nor can you replace an existing document with a replacement document that has a different _id field value.

For write operations, MongoDB preserves the order of the document fields except for the following cases:

  • The _id field is always the first field in the document.

  • Updates that include renaming of field names may result in the reordering of fields in the document.

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.