Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

$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

来年

$unwind