mongodb update push array

前端 未结 3 2042
轻奢々
轻奢々 2021-01-14 15:33

I have the following schema. I am using node.js with mongodb

attributes: {
    type: { type: \'string\' },
    title: { type:\'string\' },
    description:          


        
3条回答
  •  灰色年华
    2021-01-14 16:16

    Someone who trying to push the element into an array is possible now, using the native mongodb library.

    Considering the following mongodb collection object

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

    The following query can be used to push the array element to "attachments" at the end. $push or $addToSet can be used for this.

    This will be inserting one object or element into attachments

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

    This will be inserting each object in the array into attachments

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

提交回复
热议问题