delete inside a document - mongoDB
I'm getting a specific collection with db.collection(collectionName)- that brings me 3 objects (as you can see in the picture). I want to access a specific object(for example screen-1) and delete the first element in the commercials array according to its id. I tried to do it the following way, but it throws a note that find(..).deleteMany(..) is not a function. Anyone can help?
dbo
.collection(collectionName)
.find({ screen: client.screen })
.deleteMany({
id: commid,
})
.then((result) => {
if (result.deletedCount === 1) {
console.log("Successfully deleted one document.");
} else {
console.log(
"No documents matched the query. Deleted 0 documents."
);
}
});
client.screen contains screen-1, commid contains 1 ( i want to delete the first element in the array so its id is 1)
You need to update the document and pull the element from the array since you do not want to delete whole document:
db.collectionName.update({ screen:"screen-1" },{ $pull: { 'commercials.id': 1 }} );