sql >> Base de Datos >  >> NoSQL >> MongoDB

matriz de inserción de actualización de mongodb

Alguien que intente insertar el elemento en una matriz ahora es posible, utilizando la biblioteca mongodb nativa.

Teniendo en cuenta el siguiente objeto de colección mongodb

{ 
"_id" : 5,
"attachments": [
    { 
        "id": "xxxxxxx",
        "subtype": "book",
        "title": "xxxx",
        "body": "xxxx" ,
        "filetype" : "xxxxx"
    },
    {
        "id": "xxxxxxx",
        "subtype": "book",
        "title": "xxxx",
        "body": "xxxx",
        "filetype": "xxxxx"
    }
]
}


 arr = [{
 'id':'123456',
 'subtype':'book',
 'title'  : 'c programing',
 'body'  :' complete tutorial for c',
 'filetype' : '.pdf'
 },
{
 'id':'123457',
 'subtype':'book',
 'title'  : 'Java programing',
 'body'  :' complete tutorial for Java',
 'filetype' : '.pdf'
 }
];

La siguiente consulta se puede usar para enviar el elemento de matriz a "archivos adjuntos" al final. Se puede usar $push o $addToSet para esto.

Esto será insertar un objeto o elemento en los archivos adjuntos

db.collection('books').updateOne(
  { "_id": refid }, // query matching , refId should be "ObjectId" type
  { $push: { "attachments": arr[0] } } //single object will be pushed to attachemnts
 ).done(function (err, updElem) {
  console.log("updElem" + JSON.stringify(updElem));     
});

Esto insertará cada objeto en la matriz en archivos adjuntos

   db.collection('books').updateOne(
     { "_id": refid }, // query matching , refId should be "ObjectId" type
     { $push: { "attachments":{$each: arr} } } // arr will be array of objects
     ).done(function (err, updElem) {
           console.log("updElem" + JSON.stringify(updElem));     
    });