首页 > 解决方案 > 如果 $unset 运算符的结果导致空的嵌入文档,有没有办法让 Update 方法删除父字段

问题描述

假设我在 MongoDB 中有以下文档:

{
    _id: 1,
    answer: 42,
    parent: {
        lock: true
    }
}

运行后

updateOne({_id: 1}, {$unset: {'parent.lock': ""}});

文件变为:

{
    _id: 1,
    answer: 42,
    parent: {}
}

只有当更新注释的结果是空对象而不是进行第二次调用时,有没有办法让“父”字段也被删除?

换句话说,我希望原始文档变为:

{
    _id: 1,
    answer: 42
}

但是,如果父字段的嵌入文档也有其他字段(原来是):

{
    _id: 1,
    answer: 42,
    parent: {
        lock: true,
        child: 'other'
    }
}

那么更新命令的结果将是:

{
    _id: 1,
    answer: 42,
    parent: {
        child: 'other'
    }
}

标签: mongodb

解决方案


这可以通过更新聚合管道来完成:

updateOne({_id: 1}, [
    // Remove the desired field(s).
    // Note different syntax from original command
    { $unset : [ 'parent.lock' ] },
    
    // If the parent is now an empty document, then mark it to be removed, otherwise, set it equal to itself
    { $addFields: { parent: { $cond: {
        if: { $eq: [ '$parent', {}] },
        then: '$$REMOVE',
        else: '$parent'
    }}}} 

    // Short-hand notation of $cond command above:
    // { $addFields: { parent: { $cond: [ {$eq: [ '$parent', {}] }, '$$REMOVE', '$parent' ] }}} 
])

如果其他人有更好/更优化的建议,请推荐。


推荐阅读