文档菜单
文档首页
/
MongoDB 手册
/ / /

$unset(聚合)

本页内容

  • 定义
  • 语法
  • 注意事项
  • 示例

注意

区分

以下页面指的是聚合阶段$unset。对于更新操作符$unset,请参阅$unset

$unset

从文档中删除/排除字段。

$unset 阶段具有以下语法

  • 要删除单个字段,$unset 接收一个指定要删除字段的字符串

    { $unset: "<field>" }
  • 要删除多个字段,$unset 接收一个要删除的字段数组。

    { $unset: [ "<field1>", "<field2>", ... ] }

$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" } }

以下示例删除了顶层字段isbncopies

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

返回

$unionWith