Dawn17
Dawn17

Reputation: 8297

Using pymongo to overwrite a document when it already exist just by using `insert`

I am using pymongo to insert documents that I fetched from somewhere regularly.

This could be adding a new element or replacing documents that already exist in my database.

Right now, I do

db.test.insert({
    'username': 'test',
    'data': [{...}, {...}, {...}, {...}]
})

which inserts a document successfully.

I know there is a function called replace_one but does not serve my purpose because I am regularly running this script and there could be something to be updated and something new, so I would just use insert and update whenever the document with the same username already exist.

How can I just use insert to do this, or is there a better way of doing this?

Upvotes: 1

Views: 3777

Answers (1)

Hamon
Hamon

Reputation: 301

You can use update_one and passing upsert=true parameter to it. According to the documentation:

update_one(filter, update, upsert=False, bypass_document_validation=False, collation=None, array_filters=None, session=None)

  • filter: A query that matches the document to update.
  • update: The modifications to apply.
  • upsert (optional): If True, perform an insert if no documents match the filter.

So in your case it would be:

db.test.update_one(
  {'username': 'test'},
  ,{
    'username': 'test',
    'data': [{...}, {...}, {...}, {...}]
  },
  upsert=True
)

First, it will try to find a document with that username and update it and if that was unsuccessful it will create one.

Upvotes: 2

Related Questions