Mapin
Mapin

Reputation: 85

MongoDB UpdateOne with an specific Upsert behaviour

this is the behaviour that I'm looking for:

1- Update the database, filtering by unique id, in case does not exist create new document(all the fields).

2- If the document exists, only update one especific field.

The problem that I encounter is that if I use:

collection.update_one( {'id':document['id']},
{"$set":{'field_to_update':document['field_to_update']}}, upsert:True)

Whenever the document does not exist it will create a new document but only with the field_to_update as its content. And I need to update only a field(this is because there are fields that changes a lot and I'm not interested to update) but on the other case create a complete document.

Does anyone how to achieve this?

Regards.

Upvotes: 1

Views: 398

Answers (1)

Puneet Singh
Puneet Singh

Reputation: 3543

You can use $setOnInsert to add extra fields when a new document is inserted due to upsert, Try to use it with UpdateOne if it doesn't, you can use a query like below sample

 collection.findAndModify({
    'query': { 'id':document['id'] },
    'update': {
        "$set":{'field_to_update':document['field_to_update']},
        '$setOnInsert': {
            'field_to_add': document['field_to_add'],
            'field_to_add_more': document['field_to_add_more']
            }
        },
    'new': True,
    'upsert': True,
})

Upvotes: 2

Related Questions