Mario Perez
Mario Perez

Reputation: 93

Mongodb: add field to matching child element

I have this Mongodb document

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [ 
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ"
        }
    ]
}

I need to add this field: "imagenDNI": "uploads\file-1512427693006.png" to the child that matches "dni_representante":"42541774", so this would be the result:

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [ 
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541774",
            "nombres_representante" : "ROBERTO GOMEZ",
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}

I try this code

db.getCollection('empresas')
    .update({ "representantes.dni_representante" : "42541773" }
        , {$set: {"representantes.$": { "imagenDNI": 'uploads\file-1512427693006.png' }}})

But instead of adding the field, it replaces the whole child fields, showing this:

{
    "_id" : ObjectId("5a22e86c64b6d80e384f504a"),
    "ruc" : "20455412215",
    "razon_social" : "EMPRESA A",
    "representantes" : [ 
        {
            "tipo_representante" : "accionista",
            "dni_representante" : "42541773",
            "nombres_representante" : "MARIO PEREZ"
        },
        {
            "imagenDNI": "uploads\file-1512427693006.png"
        }
    ]
}

How can I add the field instead of replacing?

Upvotes: 0

Views: 468

Answers (1)

Due to https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S you should use

db.collection.update( { <query selector> },
                      { <update operator>: { "array.$.field" : value } })

So you may try:

db.getCollection('empresas')
.update({ "representantes.dni_representante" : "42541773" }
    , {$set: {"representantes.$.imagenDNI": 'uploads\file-1512427693006.png' }})

Upvotes: 1

Related Questions