I am trying to insert, update values in the MongoDB array.
My MongoDB version is 4.0.5.
Here is my collection :
{
'id': 1,
'array': [{
'code': 'a'
}, {
'code': 'b'
}]
}
I am trying to make some upsert queries to insert/update into an array but I don't found a good solution until then.
My filters are :
'id'(to point the correct document)'array.code'(to point the correct array cell)
- If the document exists in the collection but there is no cell with
'code': 'c'
db.test.update({
'id': 1
}, {
$set: {'array.$[elem].test':'ok'}
}, {
upsert: true,
arrayFilters: [{'elem.code': 'c'}]
}
)
I have no error but no upsert too.
I want to insert the element in the array like this :
// Desired result
{
'id': 1,
'array': [{
'code': 'a'
}, {
'code': 'b'
}, {
'code': 'c'
'test': 'ok'
}]
}
- If the document doesn't exist in the collection
db.test.update({
'id': 3
}, {
$set: {'array.$[elem].test':'ok'}
}, {
upsert: true,
arrayFilters: [{'elem.code': 'a'}]
}
)
In that case, I have this error :
WriteError: The path 'array' must exist in the document in order to apply array updates., full error: {'index': 0, 'code': 2, 'errmsg': "The path 'array' must exist in the document in order to apply array updates."}
I want to upsert a new document with elements of the query like this :
// Desired result
{
'id': 3,
'array': [{
'code': 'a'
'test': 'ok'
}]
}
upsert: true in the query parameters doesn't seem to work with the array.
Your help will be highly appreciated.
upsert: trueapplies to the document, i.e. you insert a new document if it does not exist. It does not apply to an element in an array.