

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1unset
<a name="unset-update"></a>

Amazon DocumentDB 中的`$unset`运算符用于从文档中删除指定字段。使用删除字段时`$unset`，该字段将从文档中删除，并相应地减小文档的大小。当你想从文档中删除不必要的数据时，这可能很有用。

**参数**
+ `field`：要从文档中移除的字段。这可以是单个字段，也可以是嵌套字段的虚线路径。

## 示例（MongoDB 外壳）
<a name="unset-examples"></a>

以下示例演示如何使用`$unset`运算符从`example`集合中的文档中移除该`Words`字段。

**创建示例文档**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**查询示例**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**输出**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

在此示例中，`$unset`运算符用于从文档中移除`DocName`等于 “文档 1” 的`Words`字段。生成的文档不再包含该`Words`字段。

## 代码示例
<a name="unset-code"></a>

要查看使用该`$unset`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function removeField() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('example');

  const result = await collection.updateOne(
    { "DocName": "Document 1" },
    { $unset: { "Words": 1 } }
  );

  console.log(`Modified ${result.modifiedCount} document(s)`);
  client.close();
}

removeField();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def remove_field():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['example']

    result = collection.update_one(
        {"DocName": "Document 1"},
        {"$unset": {"Words": 1}}
    )

    print(f"Modified {result.modified_count} document(s)")
    client.close()

remove_field()
```

------