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: {

最低0.47元/天 解锁文章
1665

被折叠的 条评论
为什么被折叠?



