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 canset
the insertion position of element in thearray
.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 4values
like [0,1,2,3]Python Code Example
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 codearray.insert(-1,5)
the array elements isarray [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 thearray
with4 document
values. As you can see in belowMongoDB Code Example
Here i have given example of
Python
withMongoDB
.Hope this will help out to you.
For further you ref Array Update Operators