Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cập nhật số lượng trong MongoDB dựa trên 2 điều kiện

Sử dụng update() với query kết hợp điều kiện tài liệu cha (_id) và điều kiện phần tử mảng (Information.id) để cập nhật chính xác. Tạo collection kho hàng:

> db.demo605.insertOne({
...   _id:1,
...   "Information": [
...     { "id": "Product-1", "Quantity": 50 },
...     { "id": "Product-2", "Quantity": 100 }
...   ]
... });
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo605.insertOne({
...   _id:2,
...   "Information": [
...     { "id": "Product-1", "Quantity": 30 },
...     { "id": "Product-2", "Quantity": 40 }
...   ]
... });
{ "acknowledged" : true, "insertedId" : 2 }

Hiển thị dữ liệu:

> db.demo605.find();

Cập nhật: _id=1 VÀ Information.id="Product-1" → Quantity=1000:

> db.demo605.update(
...   {_id:1, "Information.id":"Product-1"},
...   {$set:{"Information.$.Quantity":1000}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả (chỉ _id=1, Product-1 bị đổi):

> db.demo605.find().pretty();

Cơ chế:

  • Query: {_id:1, "Information.id":"Product-1"} - tìm tài liệu _id=1 CÓ chứa phần tử Information.id="Product-1"
  • Update: {$set:{"Information.$.Quantity":1000}} - $ trỏ đến phần tử Information khớp "Product-1" trong tài liệu đã tìm thấy
  • Chỉ 1 phần tử được cập nhật (phần tử đầu tiên khớp trong mảng)