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
返回错误。 - 如果
field
在input
中不存在,则$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