如何自己建公司网站,徐州建设局网站,摄影网站开发背景,西昌手机网站设计使用$unset阶段可移除文档中的某些字段。从版本4.2开始支持。
语法
移除单个字段#xff0c;可以直接指定要移除的字段名#xff1a;
{ $unset: field }移除多个字段#xff0c;可以指定一个要移除字段名的数组#xff1a;
{ $unset: [ …使用$unset阶段可移除文档中的某些字段。从版本4.2开始支持。
语法
移除单个字段可以直接指定要移除的字段名
{ $unset: field }移除多个字段可以指定一个要移除字段名的数组
{ $unset: [ field1, field2, ... ] }用法 u n s e t 和 unset和 unset和project
对于移除字段$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 } }移除顶层字段
下面的例子移除顶层字段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、内嵌字段firstname文档内的以及内嵌字段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 } ] }