Ortal Cohen
Ortal Cohen

Reputation: 25

delete inside a document - mongoDB

enter image description here

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)

Upvotes: 0

Views: 93

Answers (1)

R2D2
R2D2

Reputation: 10737

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

Upvotes: 1

Related Questions