Kai021195
Kai021195

Reputation: 833

How to pull from array of objects with array of objects in MongoDB?

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.

Upvotes: 0

Views: 1460

Answers (2)

Animesh Dey
Animesh Dey

Reputation: 1

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

Upvotes: 0

cmgchess
cmgchess

Reputation: 10247

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

Upvotes: 1

Related Questions