$unset (aggregation)

On this page本页内容

Definition定义

Disambiguation消除歧义

The following page refers to the aggregation stage $unset. 下一页指的是聚合阶段$unsetFor the update operator $unset, see $unset.有关更新运算符$unset,请参阅$unset

$unset

New in version 4.2.版本4.2中的新功能。

Removes/excludes fields from documents.从文档中删除/排除字段。

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:以下示例删除顶级字段isbncopies

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(从名称文档中)和嵌入字段warehouse(从副本数组中的元素中):

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 } ] }