MongoDB聚合:$unset

使用$unset阶段可移除文档中的某些字段。从版本4.2开始支持。

语法

  • 移除单个字段,可以直接指定要移除的字段名:
    { $unset: "" }
    
    • 移除多个字段,可以指定一个要移除字段名的数组:
      { $unset: [ "", "", ... ] }
      

      用法

      u n s e t 和 unset和 unset和project

      对于移除字段,$unset相当于是$project的别名:

      { $project: { "": 0, "": 0, ... } }
      

      内嵌字段

      要移除或排除内嵌文档的字段,可以使用点号:

      { $unset: "" }
      

      或:

      { $unset: [ "", ...] }
      

      举例

      使用下面的命令创建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 } ] }