Remove documents embedded in Mongodb

Asked

Viewed 99 times

-1

I have a collection 'collection', with documents of the type:

{
   'autor':'Fulano',
   'livros':[
      {'Título':'Livro A','páginas':200},
      {'Título':'Livro B','páginas':150},
      {'Título':'Livro C','páginas':300},
   ]
}

I want to remove one of these embedded documents (for example, Book C. I’m trying to do this with the $pull command, but it always gives some error message. Somebody help me?

  • Put next to the question the way you are trying to remove, so it is possible to check if you are running the right command ;)

1 answer

1

Initially, you can try this way:

db.acervo.remove({'livros.Título': 'Livro C'})

You can also use the update function along with $pull to remove all exact matches from a specified array value; In this case, it will remove the document whose Title key has the value "Book C".

db.acervo.update({}, 
{$pull: {livros: {Título: 'Livro C'}}})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.