Hướng dẫn mongodb unset

This entry is part 16 of 24 in the series MongoDB

Show
  • MongoDB là gì? Các khái niệm trong MongoDB
  • Hướng dẫn cài đặt, cấu hình MongoDB trên Windows 10
  • Cài đặt và sử dụng Robo 3T (RoboMongo) trên Windows
  • Hướng dẫn cài đặt MongoDB trên Linux (Ubuntu 16.04)
  • Hướng dẫn MongoDB – Tạo database trong MongoDB
  • Hướng dẫn MongoDB – Xóa, DROP database trong MongoDB
  • Tạo bảng, collections trong MongoDB (Tạo bằng dòng lệnh, Robo3t)
  • Xóa bảng, collections trong MongoDB (Xóa bằng lệnh/ Robo3T)
  • Insert document, bản ghi trong MongoDB (Insert bằng lệnh, Robo3T)
  • Truy vấn dữ liệu/document, find(), Select, Where trong MongoDB
  • Xóa document, row trong MongoDB (bằng dòng lệnh, Robo3T)
  • Update document, dữ liệu trong MongoDB
  • Projection trong MongoDB (SELECT field/column trong MongoDB)
  • Sắp xếp trong MongoDB(orderBy, sorting() trong MongoDB)
  • Ưu nhược điểm của MongoDB, khi nào nên dùng MongoDB
  • Xóa cột, field, trường của collections trong MongoDB ($unset)
  • Kiểm tra null, check tồn tại trong MongoDB với $exists
  • Đổi tên field trong MongoDB với $rename
  • Tạo user/roles, phân quyền người dùng trên MongoDB
  • Các loại roles, vai trò, quyền trong MongoDB.
  • Đăng nhập mongodb với username và password (database mongo)
  • Tạo Replica Set trong MongoDB, Ví dụ Replica Set MongoDB
  • Replication, Replica Set trong MongoDB là gì?
  • Phân trang trong MongoDB (skip(), limit() paging trong MongoDB)

Xóa cột, field, trường của collections trong MongoDB ($unset).

(Trong mongodb data lưu dưới dạng JSON nên sẽ không có khái niệm cột, tuy nhiên khi hiển thị ta sẽ thấy mỗi field tương đương với 1 cột)

Để xóa một field trong collections ta sử dụng lệnh update() kết hợp với $unset

Cú pháp:

db.collection_name.update(
   ,
   { $unset: { : "", ... } },
    multi: 
)

Trong đó:

  • collection_name là tên của collection
  • SELECTION_CRITERIA: là mệnh đề where trong MongoDB dùng để chọn ra những document được xóa field
  • $unset: danh sách các field sẽ bị xóa
  • multi: (boolean): mặc định là false. Nếu là true thì mới cho phép xóa field ở nhiều documents

Ví dụ:

Mình insert 5 bản ghi sau vào document player

db.player.insert([
{'_id':'1', 'name':'neymar', 'country':'brazil', 'age':'25'},
{'_id':'2', 'name':'hazard', 'country':'belgium', 'age':'25'},
{'_id':'3', 'name':'mbappe', 'country':'france', 'age':'18'},
{'_id':'4', 'name':'modric', 'country':'croatia', 'age':'30'},
{'_id':'5', 'name':'ronaldo', 'country':'portugal', 'age':'33'}])

Hướng dẫn mongodb unset

Để xóa fields age ta dùng lệnh sau:

db.player.updateMany({},{$unset:{age:""}})
hoặc:
db.player.update({},{$unset:{age:""}},{multi: true})

* Lưu ý: Các bạn nhớ là dùng lệnh updateMany() hoặc lệnh update() với tùy chọn {multi: true} nếu không nó sẽ chỉ xóa field age của document đầu tiên mà thôi

Kết quả: trường age bị xóa khỏi tất cả các document trong collections player

Okay, Done!

References:

https://docs.mongodb.com/manual/reference/operator/update/unset/

Docs HomeMongoDB Manual

Note

Disambiguation

The following page refers to the update operator $unset. For the aggregation stage $unset, available starting in MongoDB 4.2, see $unset.

$unset

The $unset operator deletes a particular field. Consider the following syntax:

{ $unset: { : "", ... } }

The specified value in the $unset expression (i.e. "") does not impact the operation.

To specify a in an embedded document or in an array, use dot notation.

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.

If the field does not exist, then $unset does nothing (i.e. no operation).

When used with $ to match an array element, $unset replaces the matching element with null rather than removing the matching element from the array. This behavior keeps consistent the array size and element positions.

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $unset with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).

Create the products collection:

db.products.insertMany( [
{ "item": "chisel", "sku": "C001", "quantity": 4, "instock": true },
{ "item": "hammer", "sku": "unknown", "quantity": 3, "instock": true },
{ "item": "nails", "sku": "unknown", "quantity": 100, "instock": true }
] )

Update the first document in the products collection where the value of sku is unknown:

db.products.updateOne(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } }
)

updateOne() uses the $unset operator to:

  • remove the quantity field

  • remove the instock field

{
item: 'chisel',
sku: 'C001',
quantity: 4,
instock: true
},
{
item: 'hammer',
sku: 'unknown'
},
{
item: 'nails',
sku: 'unknown',
quantity: 100,
instock: true
}

Tip

See also: