Javascript 如何在MongoDB中从数组中删除除X以外的所有对象?

Javascript 如何在MongoDB中从数组中删除除X以外的所有对象?,javascript,arrays,mongodb,mongoose,Javascript,Arrays,Mongodb,Mongoose,我有一个如下所示的模型模式: title: { Type: String } description: {Type: String} .... .... workingwith: [ { user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } } ], 我正在尝试构建一个更新函数,该函数删除使用数组中的所有对象,但特定对象除外: await Job.findByIdAndUpdate

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

title: { Type: String }
description: {Type: String}
....
....
workingwith: [
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  }
],
我正在尝试构建一个更新函数,该函数删除
使用
数组中的所有对象,但特定对象除外:

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 } }
提前谢谢。

试试看

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

我是通过在文档中为
$pull
提供一个示例来实现这一点的。

Ja,在发布我的问题之前,我尝试了与您的解决方案类似的方法,但没有成功,因为我切换了语法,这就是我以前所做的:
$pull:{workingwith:{$ne:{user:request.user}}}
lol