Database Manual / Reference / Query Language / Update / Fields

$unset (update operator)(更新运算符)

Definition定义

Note

Disambiguation消歧

The following page refers to the update operator $unset. For the aggregation stage, see $unset.以下页面涉及更新运算符$unset。关于聚合阶段,请参阅$unset

$unset
The $unset operator deletes a particular field.$unset运算符删除特定字段。

Compatibility兼容性

You can use $unset for deployments hosted in the following environments:您可以将$unset用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

Consider the following syntax:考虑以下语法:

{ $unset: { <field1>: "", ... } }

The specified value in the $unset expression (i.e. "") does not impact the operation.$unset表达式中的指定值(即“”)不会影响操作。

To specify a <field> in an embedded document or in an array, use dot notation.要在嵌入式文档或数组中指定<field>,请使用点符号

Behavior行为

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.从MongoDB 5.0开始,更新运算符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

If the field does not exist, then $unset does nothing (i.e. no operation).如果字段不存在,则$unset什么也不做(即没有操作)。

When used with $ to match an array element, $unset replaces the matching element with null rather than removing the matching element from the array. 当与$一起使用以匹配数组元素时,$unset会将匹配的元素替换为null,而不是从数组中删除匹配的元素。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 ( { } ). 从MongoDB 5.0开始,当您使用像$unset这样的更新运算符和空操作数表达式({})时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

Example示例

Create the products collection:创建products集合:

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:更新products集合中sku值是unknown的第一个文档:

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

updateOne() uses the $unset operator to:updateOne()使用$unset运算符来:

  • remove the quantity field删除quantity字段
  • remove the instock field删除instock字段
{
item: 'chisel',
sku: 'C001',
quantity: 4,
instock: true
},
{
item: 'hammer',
sku: 'unknown'
},
{
item: 'nails',
sku: 'unknown',
quantity: 100,
instock: true
}