4

I'm wondering if there exists a $setIfNullOrEmpty operator. I'm currently using an upsert like this:

const filter = {
    id: 123
}
const updates = {
    $set: {
        varx: valx
    },
    $inc: { vary: valy },
    $setOnInsert: z
};
const options = { upsert: true };
collection.updateOneWithOptions(filter, updates, options);

I would like to also have an option to $set some value if in the database it's null or an empty string. My ideal updates object would look like this (does something like this exist?):

const updates = {
        $set: {
            varx: valx
        },
        $setIfNullOrEmpty: {
            varxy: varxy
        }
        $inc: { vary: valy },
        $setOnInsert: z
    };

I understand that I could make 2 queries (1 to grab the item I'm looking for, check for that property and another to update the item) but I'm looking for a way to make 1 query. Is there a way to do this?

2 Answers 2

4

This can be achieved using $cond operator

Try the below command

const filter = {
    id: 123
}
const updates = {
    $cond: {
        if: {
            $or:[{$eq: ["varxy",null]},{$eq: ["varxy",""]}]
        },
        then: {
            $set: {
                varxy: varxy
            }
        },
        else: {
            $set: {
                varx: valx
            }
        }
    },
    $inc: { vary: valy },
    $setOnInsert: z
};
const options = { upsert: true };
collection.updateOneWithOptions(filter, updates, options);
Sign up to request clarification or add additional context in comments.

Comments

0

According to the docs:

The $inc operator increments a field by a specified value.

If the field does not exist, $inc creates the field and sets the field to the specified value.

So your current query works. If the found document doesn't have field vary, it would be created and set with your specified value.

1 Comment

Thanks for the answer, unfortunately I don't think that answers the question. I'm looking for a $set that would work if the field was null or empty. The $inc works only with integers and will only set the field if it doesn't exists. Not if the field is null or an empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.