$unset (aggregation)
On this page本页内容
Definition定义
Syntax语法
The $unset
stage has the following syntax:$unset
阶段具有以下语法:
Considerations注意事项
$unset
and $project
The $unset
is an alias for the $project
stage that removes/excludes fields:$unset
是$project
阶段的别名,用于删除/排除字段:
{ $project: { "<field1>": 0, "<field2>": 0, ... } }
Embedded Fields嵌入式字段
To remove/exclude a field or fields within an embedded document, you can use the dot notation, as in:要删除/排除嵌入文档中的一个或多个字段,可以使用点表示法,如:
{ $unset: "<field.nestedfield>" }
or或
{ $unset: [ "<field1.nestedfield>", ...] }
Examples实例
Create a sample 使用以下文档创建示例books
collection with the following documents:books
集合:
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删除单个字段
The following example removes the top-level field 以下示例删除顶级字段copies
:copies
:
db.books.aggregate([ { $unset: "copies" } ])
Alternatively, you can also use the following syntax:或者,您也可以使用以下语法:
db.books.aggregate([ { $unset: [ "copies" ] } ])
Either operation returns the following documents:任一操作都会返回以下文档:
{ "_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删除顶级字段
The following example removes the top-level fields 以下示例删除顶级字段isbn
and copies
:isbn
和copies
:
db.books.aggregate([
{ $unset: [ "isbn", "copies" ] }
])
The $unset
operation outputs the following documents:$unset
操作输出以下文档:
{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } }
{ "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }
Remove Embedded Fields删除嵌入字段
The following example removes the top-level field 以下示例删除了顶级字段isbn
, the embedded field first
(from the name
document) and the embedded field warehouse
(from the elements in the copies
array):isbn
、嵌入字段first
(从name
文档中)和嵌入字段warehouse
(从copies
数组中的元素中):
db.books.aggregate([
{ $unset: [ "isbn", "author.first", "copies.warehouse" ] }
])
The $unset
operation outputs the following documents:$unset
操作输出以下文档:
{ "_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 } ] }