2017-12-05 2 views
0

zu passenden habe ich dieses MongoDB DokumentMongoDB: add Feld untergeordnetes Element

{ 
    "_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" 
     } 
    ] 
} 

Ich brauche dieses Feld hinzufügen: "imagenDNI": "uploads \ file-1512427693006.png" mit dem Kind, das übereinstimmt "dni_representante": "42541774", so würde dies das Ergebnis sein:

{ 
    "_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" 
     } 
    ] 
} 

ich versuche, diesen Code

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

Aber statt das Feld hinzuzufügen, ersetzt es die ganze Kind Felder, dies zeigt:

{ 
    "_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" 
     } 
    ] 
} 

Wie kann ich das Feld anstatt sie zu ersetzen hinzufügen?

Antwort

1

Aufgrund https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S Sie

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

verwenden, sollten Sie können also versuchen:

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

Danke, Khánh! Es funktionierte! –

+0

Bei imageDNDN ist eine Variable Feldname enthalten. Sie können verweisen https://stackoverflow.com/questions/17039018/how-to-use-a-variable-as-a-field-name-in-mongodb-native-findone –

+0

Sie sind die Besten! Vielen Dank! Genau das, was ich brauchte. Ich würde die Suche selbst machen, aber du hast mir gerade Zeit gespart. –

Verwandte Themen