MongoDB – How to Insert Into Array of Objects

arraymongodb

I have

{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [ 
        {
            "name" : "We",
            "arr" : [ 
                "5a26d554677475818a795f75", 
                "5a395bb0976d5304c07f7dd4"
            ]
        }, 
        {
            "name" : "sandeep",
            "arr" : [ 
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

I want to add an element inside list.arr where name = 'we' and add only if the element does not exist

how do i perform this query.

Best Answer

As MongoDB BOL $position MongoDB 3.6 adds fuctionality to the dollar option($position Operator) directing the push operation to insert the element at the end of the array.

Note: $position Operator is a new features in MongoDB 3.6.0. Through which you can set the insertion position of element in the array.

Let's from beginning onward,here i want to show you . How you shall insert element in MongoDB. Along with MongoDB i am also giving simple example of Pyhon for your better understanding.

Suppose that in Python we have array object with 4 values like [0,1,2,3]

Python Code Example

Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> array = [1,2,3,4]
>>> array[-1]
4
>>> array.insert(-1,5)
>>> array
[1, 2, 3, 5, 4]
>>> 

This is the Python example here when saw array[-1]. It will show 4. i want to insert the number 5 before the last element in array. As you can see in Python. After insert the code array.insert(-1,5) the array elements is array [1,2,3,5,4].

Likewise i want to insert the sample array element in MongoDB.

Here first i have created the position collection in my MongoDB database. Then insert the array with 4 document values. As you can see in below

MongoDB Code Example

> db.createCollection("position")
{ "ok" : 1 }
> db.position.insert({array : [1,2,3,4]})
WriteResult({ "nInserted" : 1 })
> db.position.findOne()
{
        "_id" : ObjectId("5a40c6288367f8d601e1e513"),
        "array" : [
                1,
                2,
                3,
                4
        ]
}
> db.position.update({},
... {$push : {array : {$each: [5], $position: -1 }}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.position.findOne()
{
        "_id" : ObjectId("5a40c6288367f8d601e1e513"),
        "array" : [
                1,
                2,
                3,
                5,
                4
        ]
}
>

Note : Remember that push with no dollar position value specified already appends values to the end of the array.

With negative values of dollar position i have more options as far as where to insert a value in the array.If the absolute value of the negative integer specified by the dollar poistion is greater than then the push inserts the object at the beginning of the array.

Here i have given example of Python with MongoDB.

Hope this will help out to you.

For further you ref Array Update Operators