3

I want to remove a value from the teamUsers array, but I'm struggling because the teamUsers array is within an object which is within an array itself.

The data in Mongo is below. I want to pull user "105" from Team Two.

    Client: {
      teams: [
        { teamID: 123,
          teamName: "Team One",
          teamUsers: [
            "101",
            "102",
            "103"
          ]
        },
        { teamID: 456,
          teamName: "Team Two",
          teamUsers: [
            "104",
            "105",
            "106"
          ]
        }
      ]
    }

I'd appreciate any help out there. My current attempt so far, which I think will pull the entire Team Two. I'm stuck as to how to go further deeper in order to only pull a value from an array inside Team Two:

    let removeUserFromOldTeamUsersArray = await Client.findOneAndUpdate(searchQuery,
      {
        $pull: {
          "teams" {"teamName": "Team Two"}
        }
      }
    )
turivishal
  • 34,368
  • 7
  • 36
  • 59
James
  • 106
  • 7
  • 1
    From [one of the answers](https://stackoverflow.com/a/58023017/122005) in the marked duplicate, try `await Client.findOneAndUpdate({ 'teams.teamName': 'Team Two' }, { '$pull': { 'teams.$[elem].teamUsers': '105' } },{ 'arrayFilters': [{ 'elem.TeamName': 'Team Two'}] })` – chridam Nov 15 '20 at 13:35
  • *chridam* is right, as per duplicate question this is good answer, @James your working query probably [playground](https://mongoplayground.net/p/gyvnXyk60pf) – turivishal Nov 15 '20 at 13:41
  • @chridam thank you for referring me to this. The question was perfectly duplicated to my problem and answered it. – James Nov 15 '20 at 17:16
  • @turivishal Yes, thank you though for your playground. Great help from both. – James Nov 15 '20 at 17:17

0 Answers0