$unset(聚合)
在此页面上
定义
语法
$unset
阶段采用以下语法:
Considerations
$unset
和 $project
$unset
是 $project
阶段的别名,用于删除/排除字段:
{ $project: { "<field1>": 0, "<field2>": 0, ... } }
嵌入字段
如需删除/排除嵌入式文档中的一个或多个字段,可以使用点符号,例如:
{ $unset: "<field.nestedfield>" }
or
{ $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 } ] }