本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$unset
Amazon DocumentDB 中的$unset运算符用于从文档中删除指定字段。使用删除字段时$unset,该字段将从文档中删除,并相应地减小文档的大小。当你想从文档中删除不必要的数据时,这可能很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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字段。
代码示例
要查看使用该$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()