Definition 定义

NOTE 歧义澄清 以下页面指的是 aggregation stage $unset。 对于 update operator $unset,请参阅 $unset

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

Syntax 语法

$unset stage 的语法如下:

  • 要删除单个字段, $unset 需要一个字符串来指定要删除的字段:

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

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

    Considerations 注意事项

    $unset and $project $unset$project

    $unset$project stage 删除/排除字段的别名:

    1. { $project: { "<field1>": 0, "<field2>": 0, ... } }

    Embedded Fields 嵌入式字段

    要删除/排除嵌入文档中的一个或多个字段,您可以使用点符号,如下所示:

    1. { $unset: "<field.nestedfield>" }

    或者

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

    Example 例子

    使用以下文档创建示例 books collection:

    1. db.books.insertMany([
    2. { "_id" : 1, title: "Antelope Antics", isbn: "0001122223334", author: { last:"An", first: "Auntie" }, copies: [ { warehouse: "A", qty: 5 }, { warehouse: "B", qty: 15 } ] },
    3. { "_id" : 2, title: "Bees Babble", isbn: "999999999333", author: { last:"Bumble", first: "Bee" }, copies: [ { warehouse: "A", qty: 2 }, { warehouse: "B", qty: 5 } ] }
    4. ])

    Remove a Single Field 移除单个字段

    以下示例删除顶级字段 copies

    1. db.books.aggregate([ { $unset: "copies" } ])

    或者,您也可以使用以下语法:

    1. db.books.aggregate([ { $unset: [ "copies" ] } ])

    任一 operation 都会返回以下文档:

    1. { "_id" : 1, "title" : "Antelope Antics", "isbn" : "0001122223334", "author" : { "last" : "An", "first" : "Auntie" } }
    2. { "_id" : 2, "title" : "Bees Babble", "isbn" : "999999999333", "author" : { "last" : "Bumble", "first" : "Bee" } }

    Remove Top-Level Fields 移除顶级字段

    以下示例删除顶级字段 isbncopies

    1. db.books.aggregate([
    2. { $unset: [ "isbn", "copies" ] }
    3. ])

    $unset operation 输出以下文档:

    1. { "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } }
    2. { "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }

    Remove Embedded Fields 移除嵌入式字段

    下面的例子删除了顶级字段 isbn,嵌入字段 first(从 author 文档中)和嵌入字段 warehouse(从 copies 数组的元素中):

    1. db.books.aggregate([
    2. { $unset: [ "isbn", "author.first", "copies.warehouse" ] }
    3. ])

    $unset operation 输出以下文档:

    1. { "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An" }, "copies" : [ { "qty" : 5 }, { "qty" : 15 } ] }
    2. { "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble" }, "copies" : [ { "qty" : 2 }, { "qty" : 5 } ] }

    参考

    https://docs.mongodb.com/manual/reference/operator/aggregation/unset