Thomas
Thomas

Reputation: 595

MongoDB - Set if Null or Empty Query Operator

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?

Upvotes: 4

Views: 9135

Answers (2)

Mani
Mani

Reputation: 1549

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);

Upvotes: 4

Duc Nguyen
Duc Nguyen

Reputation: 855

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.

Upvotes: 0

Related Questions