5

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?

2 Answers 2

5

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 }}}
)
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Thank you for complementing the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.