MongoDB聚合运算符:$unsetField

MongoDB聚合运算符:$unsetField


$unsetField可以用来移除文档中指定的字段,字段名可以包含点号( .)和美元符号( $)。 $unsetField等价于在 $setField中使用 $$REMOVE

语法

{
   
   
   $unsetField: {
   
   
      field: <String>,
      input: <Object>,
   }
}
  • field:<String>input对象中药添加、更新或移除的字段,可以是合法的字符串表达式。
  • input: <Object>:包含要添加、更新的field字段的文档,input可以是对象、不存、null或undefined,不能是别的类型或值。

使用

  • 如果input缺失、未定义或为空,则$unsetField返回null且不会更新input
  • 如果input被解析为非对象、缺失、未定义或null,$unsetField返回错误。
  • 如果field解析为非字符串,则$unsetField返回错误。
  • 如果fieldinput中不存在,则$unsetField会添加它。
  • $unsetField不会隐式遍历对象或数组。例如,$unsetField将字段值"a.b.c"计算为顶级字段"a.b.c",而不是嵌套字段{ "a": { "b": { "c": } } }

举例

移除包含点号(.)的字段

使用下面的脚本创建inventory集合:

db.inventory.insertMany( [
   {
   
    _id: 1, item: "sweatshirt", qty: 300, "price.usd": 45.99 },
   {
   
    _id: 2, item: "winter coat", qty: 200, "price.usd": 499.99 },
   {
   
    _id: 3, item: "sun dress", qty: 250, "price.usd": 199.99 },
   {
   
    _id: 4, item: "leather boots", qty: 300, "price.usd": 249.99 },
   {
   
    _id: 5, item: "bow tie", qty: 180, "price.usd": 9.99 }
 ] )

下面的聚合使用$replaceWith管道阶段和$unsetFeild运算符移除所有文档的"price.usd"字段。

db.inventory.aggregate( [
   {
   
    $replaceWith
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值