$unset

On this page本页内容

Definition定义

Note注意
Disambiguation消除歧义

The following page refers to the update operator $unset. 以下页面涉及更新运算符$unsetFor the aggregation stage $unset, available starting in MongoDB 4.2, see $unset.对于从MongoDB 4.2开始的聚合阶段$unset,请参阅$unset

$unset

The $unset operator deletes a particular field. $unset运算符删除特定字段。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. 从MongoDB 5.0开始,更新运算符以词典顺序处理具有基于字符串的名称的文档字段。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).如果该字段不存在,则$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:使用$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
}
←  $setOnInsertArray Update Operators →