Definition 定义
NOTE 歧义澄清 以下页面指的是 aggregation stage $unset。 对于 update operator $unset,请参阅 $unset。
Syntax 语法
$unset stage 的语法如下:
要删除单个字段, $unset 需要一个字符串来指定要删除的字段:
{ $unset: "<field>" }
要删除多个字段, $unset 需要一个要删除的字段数组。
{ $unset: [ "<field1>", "<field2>", ... ] }
Considerations 注意事项
$unset
and$project
$unset
和$project
$unset 是 $project stage 删除/排除字段的别名:
{ $project: { "<field1>": 0, "<field2>": 0, ... } }
Embedded Fields 嵌入式字段
要删除/排除嵌入文档中的一个或多个字段,您可以使用点符号,如下所示:
{ $unset: "<field.nestedfield>" }
或者
{ $unset: [ "<field1.nestedfield>", ...] }
Example 例子
使用以下文档创建示例
books
collection:db.books.insertMany([
{ "_id" : 1, title: "Antelope Antics", isbn: "0001122223334", author: { last:"An", first: "Auntie" }, copies: [ { warehouse: "A", qty: 5 }, { warehouse: "B", qty: 15 } ] },
{ "_id" : 2, title: "Bees Babble", isbn: "999999999333", author: { last:"Bumble", first: "Bee" }, copies: [ { warehouse: "A", qty: 2 }, { warehouse: "B", qty: 5 } ] }
])
Remove a Single Field 移除单个字段
以下示例删除顶级字段
copies
:db.books.aggregate([ { $unset: "copies" } ])
或者,您也可以使用以下语法:
db.books.aggregate([ { $unset: [ "copies" ] } ])
任一 operation 都会返回以下文档:
{ "_id" : 1, "title" : "Antelope Antics", "isbn" : "0001122223334", "author" : { "last" : "An", "first" : "Auntie" } }
{ "_id" : 2, "title" : "Bees Babble", "isbn" : "999999999333", "author" : { "last" : "Bumble", "first" : "Bee" } }
Remove Top-Level Fields 移除顶级字段
以下示例删除顶级字段
isbn
和copies
:db.books.aggregate([
{ $unset: [ "isbn", "copies" ] }
])
$unset operation 输出以下文档:
{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } }
{ "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }
Remove Embedded Fields 移除嵌入式字段
下面的例子删除了顶级字段
isbn
,嵌入字段first
(从author
文档中)和嵌入字段warehouse
(从copies
数组的元素中):db.books.aggregate([
{ $unset: [ "isbn", "author.first", "copies.warehouse" ] }
])
$unset
operation 输出以下文档:{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An" }, "copies" : [ { "qty" : 5 }, { "qty" : 15 } ] }
{ "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble" }, "copies" : [ { "qty" : 2 }, { "qty" : 5 } ] }
参考
https://docs.mongodb.com/manual/reference/operator/aggregation/unset