ryanpcmcquen
ryanpcmcquen

Reputation: 6455

How do you populate a field if it doesn't exist in Mongo?

I am writing an aggregate for MongoDB, but am running into an issue with making sure a field is always present inside of my $project query. I would like to write something like this:

{
    'foo': '$foo.bar' || ''
}

Which would populate foo with foo.bar or an empty string if the property is not there. I've tried using $or, $cond, and $exists, but none of them are guaranteeing the presence of foo.

Upvotes: 1

Views: 1516

Answers (2)

Mostafa Babaii
Mostafa Babaii

Reputation: 158

In my opinion, $exists operator is best way to check some filed is exists or not:

db.collection.find({ 'somefiled' : { '$exists' : true }});

You will not get anything when a field does not exist.

Upvotes: -1

ryanpcmcquen
ryanpcmcquen

Reputation: 6455

Figured it out:

{
    'foo': {
        $cond: {
            'if': "$foo.bar",
            'then': "$foo.bar",
            'else': ""
        }
    }
}

Upvotes: 2

Related Questions