I'm wondering if it is possible with just one operation (or just one command) to update a document inside mongodb if the value used in the update doesn't exists in an array.
example mongodb document:
{
regs : {
someid : 12345,
dataArray : [ { id : 1 }, { id : 43 }, { id : 11 }]
}
}
Now I want only to update if the id inside dataArray is not in use already, something like:
db.regs.update({ someid : 12345 }, { $push : { dataArray : { id : INT }}})
Using the above line it's possible to check if { id : INT }
is alreay in my array and update only if it isn't?
In a couple of ways. For example you can use query matching document of interest:
db.regs.update(
{someid : 12345, 'dataArray.id': {$ne: INT}},
{$push : { dataArray : {id : INT }}}
)
or perform update using addToSet
:
db.regs.update(
{someid : 12345},
{$addToSet : {dataArray : {id : INT }}}
)
As @zero323 has already pointed out, there is an specific update operation with that specific use case in mind. From the MongoDB documentation:
$addToSet
The
$addToSet
operator adds a value to an array only if the value is not in the array already. If the value is in the array,$addToSet
returns without modifying the array.Consider the following example:
db.collection.update( { field: value }, { $addToSet: { field: value1 } } );
Here,
$addToSet
appendsvalue1
to the array stored infield
, only ifvalue1
is not already a member of this array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With