【问题标题】:How to delete all objects except X from array in MongoDB?如何从MongoDB中的数组中删除除X之外的所有对象?
【发布时间】:2020-09-04 07:37:49
【问题描述】:

我有一个如下所示的模型架构:

title: { Type: String }
description: {Type: String}
....
....
workingwith: [
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  }
],

我正在尝试构建一个更新函数,该函数删除workingwith 数组中的所有对象,除了指定的对象:

await Job.findByIdAndUpdate(
  request.resourceId,
  {
      $set: { positionFilled: true },
      $pull: { workingwith: { $elementMatch: { $not: { user: request.user } } } }
  },
  {
     new: true,
     runValidators: true
  }
);

有没有办法做我正在寻找的事情?

这是我已经尝试过的:

workingwith: { $ne: { user: request.user } }
////////
workingwith: { $not: { user: request.user } }

提前致谢。

【问题讨论】:

    标签: javascript arrays mongodb mongoose


    【解决方案1】:

    试试

    {
          $set: { positionFilled: true },
          $pull: { workingwith: { user : { $ne: request.user } } }
    }
    

    我是通过在文档here 中遵循$pull 的示例得出的。

    【讨论】:

    • Ja,在发布我的问题之前,我尝试了与您的解决方案类似的方法,但它不起作用,因为我切换了语法,这是我以前的:$pull: { workingwith: { $ne : { user: request.user } } }lol
    猜你喜欢
    • 2014-05-15
    • 2020-12-13
    • 2023-03-09
    • 2015-08-29
    • 1970-01-01
    • 2013-03-16
    相关资源
    最近更新 更多