Definition定义
Note
Disambiguation消歧
$unsetThe$unsetoperator 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, 从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删除quantityfieldquantity字段remove the删除instockfieldinstock字段
{
item: 'chisel',
sku: 'C001',
quantity: 4,
instock: true
},
{
item: 'hammer',
sku: 'unknown'
},
{
item: 'nails',
sku: 'unknown',
quantity: 100,
instock: true
}