On this page本页内容
$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>,请使用点表示法。
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, 从MongoDB 5.0开始,当使用带有空操作数表达式(mongod no longer raises an error when you use an update operator like $unset with an empty operand expression ( { } ). { })的更新运算符$unset时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。
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运算符执行以下操作:
quantity fieldquantity字段instock fieldinstock字段{
item: 'chisel',
sku: 'C001',
quantity: 4,
instock: true
},
{
item: 'hammer',
sku: 'unknown'
},
{
item: 'nails',
sku: 'unknown',
quantity: 100,
instock: true
}