A
A
a1en_yeah2020-04-16 20:42:08
MongoDB
a1en_yeah, 2020-04-16 20:42:08

How to add a field to a MongoDB subdocument without deleting already existing fields?

Help, I don't understand the logic!
I have a collection of photo galleries and each can have an array of albums.
Both galleries and albums can have their own thumbnail image to display in the list.
I add the image field to the gallery with no problems, and everything merges fine:

db.photos.update({_id:"1587050015794"},{$set:{image:"image.link"}})

But you can't add a field to an album without resetting the existing ones. The old object is replaced by a new one, so I have to send all the fields so as not to lose them ....
I send such a request.

db.photos.update({"_id" : "1587050015794","albums._id": "1587050121637"},{$set: {'albums.$':{image:"image.link"}}})


{
        "_id" : "1587050015794",
        "slug" : "1",
        "description" : {
                "fr" : "1",
                "ru" : "1"
        },
        "albums" : [
                ...,
               {
                        "_id" : "1587050121637",
                        "slug" : "11",
                        "description" : {
                                "fr" : "11",
                                "ru" : "11"
                        },
                        "gallery" : [ ]
                },
                ...
}

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-04-16
@hzzzzl

to add to $push array
https://docs.mongodb.com/manual/reference/operator...

db.photos.update(
 {_id:"1587050015794"}, 
 { $push: { 
    albums: { slug: 6666666 } 
 } 
)

A
a1en_yeah, 2020-04-16
@a1en_yeah

But I don't need to add a new album, but I need to change one property in it, or add it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question