Push object into array if the array exists otherwise create the array with object in MongoDB

前端 未结 2 731
心在旅途
心在旅途 2021-01-04 05:15

I have collection with a document like this:

{
    _id : \"abcd\",
    name : \"Tom\",
    myArray : [
        {
            field1 : \"\",
            field         


        
2条回答
  •  难免孤独
    2021-01-04 06:02

    $Push is what you need to achieve this. If the myArray is already existing then $push will insert the newObject to it( similar to the STACK data structure operation ). If the myArray doesn't exist, it will create the field "myArray" as key and will insert the newObject into it ( similar to $Set oprtaion )

    Consider another below sample document :

    {
    _id : "abcd"
    myArray:[
    {
      field1:"mango",
      field2:"apple"
    }
           ]
    }
    

    so now lets Insert the below object to it :

    var newObject = {field1:"example1" , field2:"exmaple2"};
    

    Query :

    db.collection.update({_id:"abcd"},{"$push":{myArray: newObject }});
    

    after execution of the above query, result is as below :

    {
        _id : "abcd"
        myArray:[
        {
          field1:"mango",
          field2:"apple"
        },
        {
          field1:"example1" , 
          field2:"exmaple2"
        }
               ]
        }
    

    Now let us consider another example where "myArray" key is NOT PRESENT in the document :

    {
    _id:"efg"
    }
    

    so lets insert the below object :

     var newObject2 = { field1 : "exp2" , field2 : "exp1" }
    

    Query :

     db.collection.update({_id:"efg"},{"$push":{myArray: newObject2 }});
    

    Result of the above UPDATE operation is below :

     {
       _id : "efg"
       myArray : [ 
       { 
        field1 : "exp2" , 
        field2 : "exp1"
      }
              ]
    }
    

提交回复
热议问题