$unset(聚合)
定义
语法
$unset
阶段具有以下语法
注意事项
$unset
和 $project
$unset
是一个别名,对应于用于删除/排除字段的 $project
阶段
{ $project: { "<field1>": 0, "<field2>": 0, ... } }
嵌入式字段
要从嵌入式文档中删除或排除字段,可以使用点符号,如下所示
{ $unset: "<field.nestedfield>" }
或
{ $unset: [ "<field1.nestedfield>", ...] }
示例
创建一个包含以下文档的样本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 } ] } ])
删除单个字段
以下示例删除了顶层字段copies
db.books.aggregate([ { $unset: "copies" } ])
或者,您也可以使用以下语法
db.books.aggregate([ { $unset: [ "copies" ] } ])
任意操作都返回以下文档
{ "_id" : 1, "title" : "Antelope Antics", "isbn" : "0001122223334", "author" : { "last" : "An", "first" : "Auntie" } } { "_id" : 2, "title" : "Bees Babble", "isbn" : "999999999333", "author" : { "last" : "Bumble", "first" : "Bee" } }
删除顶层字段
以下示例删除了顶层字段isbn
和copies
db.books.aggregate([ { $unset: [ "isbn", "copies" ] } ])
操作 $unset
输出以下文档
{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } } { "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }
移除嵌套字段
以下示例移除了顶层字段 isbn
、嵌套字段 first
(从 name
文档中)以及嵌套字段 warehouse
(从 copies
数组中的元素)
db.books.aggregate([ { $unset: [ "isbn", "author.first", "copies.warehouse" ] } ])
操作 $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 } ] }