0

I was trying to pull multiple objects from an array of objects, and I found this article

Using MongoDB $pull to delete documents within an Array

so here's my schema and how I did,but it does'nt work

{
        "_id": "61fed9b89763c1c3b886b74f",
        "TeamName": "Hogwarts",
        "TeamImage": "Avatar ",
        "createdAt": "2022-02-05T20:10:32.885Z",
        "updatedAt": "2022-02-05T20:59:51.359Z",
        "__v": 0,
        "TeamMember": [
            {
                "Name": "Ronne",
                "Email": "[email protected]",
                "_id": "61fee1807df64451141f08df"
            },
            {
                "Name": "Kai",
                "Email": "[email protected]",
                "_id": "61fee1e3fffd0f55ed92caee"
            },
            {
                "Name": "Selina",
                "Email": "[email protected]",
                "_id": "61fee1e3fffd0f55ed92caef"
            },
            {
                "Name": "Jessica Wu",
                "Email": "[email protected]",
                "_id": "61fee1e3fffd0f55ed92caf0"
            },
            {
                "Name": "Hormione",
                "Email": "[email protected]",
                "_id": "61fee1807df64451141f08de"
            }
        ]
    },

Delete method

const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: [ {Name: "Ronne"  },{ Name : "Hormione"} ] },
        //   $pull: { TeamMember: {$in:[ {Name: "Ronne"  },{ Name : "Hormione"} ]}},
          
        },
        { new: true,multi: true}
      );

I also try the $in method, but both don't work, did I miss something? or what's the right way to do multiple pulls using MongoDB?

BTW, I am using Mongoose for my schema, I don't know if it matters.

2 Answers 2

1

Try using this way

const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: {Name: {$in: ["Ronne","Hormione"] } } },          
        },
        { new: true,multi: true}
      );

https://mongoplayground.net/p/Sqo83w8YvVU

Sign up to request clarification or add additional context in comments.

Comments

0

DO NOT Include [ ] Brackets in $pull. It will not work

 const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: {Name: "Ronne} },          
        },
        { new: true,multi: true}
      );

1 Comment

ur syntax aint even right

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.