簡體   English   中英

如何使用 Mongoose 從陣列中刪除 object

[英]How to remove an object from an array using 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',
         },
      ]
 }

如何刪除狀態為“已終止”的 object? 此外,刪除所有狀態為“未激活”的對象是否相同?

謝謝。

您可以將 findOneAndUpdate 與 $pull 命令一起使用。

例子:

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

更多信息:

想知道下面是否也可以工作....

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM