$unset
On this page本页内容
Definition定义
$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行为
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,update运算符按照字典顺序处理具有基于字符串的名称的文档字段。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条目(这意味着该操作是无操作)。
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
fieldquantity
字段remove the删除instock
fieldinstock
字段
{
item: 'chisel',
sku: 'C001',
quantity: 4,
instock: true
},
{
item: 'hammer',
sku: 'unknown'
},
{
item: 'nails',
sku: 'unknown',
quantity: 100,
instock: true
}