1

I'm trying to delete a project object from an array.

projects:

  {
      _id : ...,
      userName: milad ,
      projets : [
        { .. projectId, pName, location .... A },
        { .. projectId, pName, location .... B },
        { .. projectId, pName, location .... C },
      ]
    }

How to delete Project B in MongoDB?

projects after remove Project B:

{
  _id : ...,
  userName: milad ,
  projets : [
    { .. projectId, pName, location .... A },
    { .. projectId, pName, location .... C },
  ]
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Miladfa7
  • 102
  • 1
  • 7

2 Answers2

1

If you have received a document from your database, you can remove an object from your array - based on the location - in such a way:

const doc = {
  _id: '507f191e810c19729de860e0',
  userName: 'milad',
  projects: [
    { _id: '507f191e810c19729de860ea', pName: 'projectA', location: 'a' },
    { _id: '507f191e810c19729de860eb', pName: 'projectB', location: 'b' },
    { _id: '507f191e810c19729de860ec', pName: 'projectC', location: 'c' }
  ]
}

// remove project b (one method, there are many more)
doc.projects = doc.projects.filter((project) => project.location !== 'b');

After the filter process you have to save it back to your mongoDB:

Mongoose: (example)

await doc.save();
Habebit
  • 957
  • 6
  • 23
0

another answer

db.collection('Profile').updateOne({ userName: username,
      "Projects.projectId": projectId }, { $pull: { 'Projects': { projectId: projectId } }})
  }
Miladfa7
  • 102
  • 1
  • 7