Search code examples
javamongodbmongodb-querymongodb-update

Run 2 mongodb updates in 1 query based on a field value


I need to update a record in mongodb where the new value depends on the value of another field in the record.

For instance given the following collection

{id: 1, list: []}
{id: 2, list: [6]}
{id: 3, list: []}
{id: 4, list: [6]}
{id: 5, list: []}

I want to be able to say:

if ('id' is in [1, 3, 5]) => add the value '6' to 'list'
else => remove the value '6' from 'list'

The outcome would be:

{id: 1, list: [6]}
{id: 2, list: []}
{id: 3, list: [6]}
{id: 4, list: []}
{id: 5, list: [6]}

This could be done in 2 update queries, as follows, but I am trying to do it in 1:

db.collection.update({$in: [1, 3, 5]}, {$addToSet: {list: 6}})
db.collection.update({$in: [2, 4]}, {$pull: {list: 6}})

The code is in Java.


Solution

  • MongoDB does not have a internal case statement as of yet which would allow you to perform this like in SQLs own case abilities.

    As such you will need to do each separately, however you can change your latter query to be more along the lines of:

    db.collection.update({$nin: [1, 3, 5]}, {$pull: {list: 6}})
    

    That should accomplish the if statement you provided better.