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

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

I have collection with a document like this:

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


        
2条回答
  •  执笔经年
    2021-01-04 05:58

    To explain all the possible cases here, the consider each document case:

    If your document to alter looks like this:

    {
        "_id": "efgh",
        "name": "Jerry"
    }
    

    Then an update statment like this:

    db.collection.update(
        { "_id": "efgh" },
        { "$push": { "myArray": { "field1": "abc", "field2": "def" } } }
    )
    

    Results in this:

    {
        "_id": "efgh",
        "name": "Jerry",
        "myArray": [
            {
                "field1": "abc",
                "field2": "def"
            }
        ]
    }
    

    So the array is created and the new item appended.

    If your document already has an array like this:

    {
        "_id": "abcd",
        "name": "Tom",
        "myArray": [
            {
                "field1": "",
                "field2": ""
            }
        ]
    }
    

    And you do basically the same statement:

    db.collection.update(
        { "_id": "abcd" },
        { "$push": { "myArray": { "field1": "abc", "field2": "def" } } }
    )
    

    Then the new document content is appended to the existing array:

    {
        "_id": "abcd",
        "name": "Tom",
        "myArray": [
            {
                "field1": "",
                "field2": ""
            },
            {
                "field1": "abc",
                "field2": "def"
            }
        ]
    }
    

    If however your original document has the named field but it is not an array, like this:

    {
        "_id": "efgh",
        "name": "Jerry",
        "myArray": 123
    }
    

    Then make sure it is not an array by testing in the query condtion and using $set instead:

    db.collection.update(
        { "_id": "efgh", "myArray.0": { "$exists": false } },
        { "$set": { "myArray": [{ "field1": "abc", "field2": "def" }] } }
    )
    

    That will safely overwrite the element that is not an array ( dot notation "myArray.0" means first array element, which is not true ) with a new array containing your content. The result is the same as the original:

    {
        "_id": "efgh",
        "name": "Jerry",
        "myArray": [
            {
                "field1": "abc",
                "field2": "def"
            }
        ]
    }
    

提交回复
热议问题