How to update a document within another document without deleting previous data in Mongodb?

Asked

Viewed 237 times

2

Actually, I have two questions: Imagine a collection livro structured:

{
    "Título" : "MongoDB para iniciantes",
    "Tags" : [ 
        "MongoDB", 
        "NoSQL"
    ],
    "Comentários" : [ 
        {
           "Comentarista" : "Ana",
           "Comentário" : "Muito bom"
        }, 
        {
           "Comentarista" : "Zé",
           "Comentário" : "Gostei demais"
        }
    ]
}

DOUBTS:

  1. How do I add a new tag, without overwriting the ones that already exist?

  2. How do I insert a new comment without overwriting existing comments?

1 answer

0

To add elements to an array in Mongodb, you can use the operator $push

$push

The $push Operator appends a specified value to an array.

Reference

You will pass the id of his document and the operator $push, second of the name and the value you want to include. To include a tag in your Document you will use the following command:

db.getCollection('livro').update(
   { _id: 1 },
   { $push: { "Tags": "SqlServer" } }
)

Now, to include a new comment in your Document, you will do exactly the above query, except that you will need to pass a object:

{ $push: { "Comentários" : { "Comentarista" : "Leonardo", "Comentário" : "Demais" } } }

There is also the operator $addToSet, which will only include a value if it is not present in the array.

Browser other questions tagged

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