MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

mongodb Update-Push-Array

Jemand, der versucht, das Element in ein Array zu schieben, ist jetzt mit der nativen Mongodb-Bibliothek möglich.

Betrachten Sie das folgende Mongodb-Sammlungsobjekt

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

Die folgende Abfrage kann verwendet werden, um das Array-Element am Ende nach "Attachments" zu verschieben. Dafür kann $push oder $addToSet verwendet werden.

Dies fügt ein Objekt oder Element in Anhänge ein

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));     
});

Dadurch wird jedes Objekt im Array in Anhänge eingefügt

   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));     
    });