Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One operation for Update if value doesn't exists in an array using mongodb

Tags:

mongodb

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?

like image 922
Maginot Junior Avatar asked Mar 22 '23 08:03

Maginot Junior


2 Answers

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 }}}
)
like image 57
zero323 Avatar answered Mar 24 '23 22:03

zero323


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 appends value1 to the array stored in field, only if value1 is not already a member of this array.

like image 45
Escualo Avatar answered Mar 24 '23 21:03

Escualo