提问者:小点点

如何使用Mongoose从数组中删除对象


我试过很多东西,但似乎没有任何一个能像预期的那样发挥作用。 假设我做了如下的事情。

{
      _id: '12345',
      name: 'John Smith',
      job: [
        {
             title: 'Web Developer',
             years: '12',
             status: 'not active',
         },
         {
             title: 'supervisor',
             years: '15',
             status: 'terminated',
         },
         {
             title: 'lead developer',
             years: '3',
             status: 'not active',
         },
         {
             title: 'Software Engineer',
             years: '9',
             status: 'active',
         },
      ]
 }

如何删除状态为“已终止”的对象? 另外,移除状态为“非活动”的所有对象也是一样的吗?

谢了。


共3个答案

匿名用户

您可以将findOneAndUpdate与$pull命令一起使用。

示例:

User.findOneAndUpdate({/* filter */}, { $pull: {array: {/* condition */}} });

更多信息:

  • $pull

匿名用户

想知道下面的方法是否也有效。。。。

Model.findOneAndUpdate({'job.status' : "terminated"}, { $pull: job.$ }, {$multi : true});

匿名用户

使用$pull运算符删除嵌套文档

var query = {
    _id: "12345"
};

var update = {
    $pull: {
        job: {
            status: {
                $in: ['terminated', 'not active']
            }
        }
    }
};

db.collection.update(query, update);