mongodb - 如果 $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'
}
}
解决方案
这可以通过更新聚合管道来完成:
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' ] }}}
])
如果其他人有更好/更优化的建议,请推荐。
推荐阅读
- javascript - 从具有日期的对象数组中获取最早的日期
- java - 为什么子类中列表的字段声明使其为空?
- stripe-payments - 检索条带中的帐户余额不起作用
- ansible - 让 ansible 跳过在运行 Ansible playbook 的机器上运行 play
- pine-script - Pine TradingView - multiple strategy.entry/exit
- javascript - res.render 传递的对象,它们叫什么?
- php - 无法从 EC2 PHP 连接到云 MongoDB
- java - 如何在 Android Studio 中为按钮创建自动动画
- matlab - 优化 FPGA 设计的建议
- r - 如何在r中分离箱线图?