$unset

On this page本页内容

Definition定义

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. Consider the following syntax:$unset运算符删除特定字段。考虑下面的语法:

{ $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行为

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.此行为使数组大小和元素位置保持一致。

Example示例

The following update() operation uses the $unset operator to remove the fields quantity and instock from the first document in the products collection where the field sku has a value of unknown.下面的update()操作使用$unset运算符从products集合中的第一个文档中删除字段quantityinstock,其中字段sku的值为unknown

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