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 },
]
}
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();
another answer
db.collection('Profile').updateOne({ userName: username,
"Projects.projectId": projectId }, { $pull: { 'Projects': { projectId: projectId } }})
}