Reputation: 8593
I am working on a kind of initialization routine for a MongoDB using mongoengine.
The documents we deliver to the user are read from several JSON files and written into the database at the start of the application using the above mentioned init routine.
Some of these documents have unique keys which would raise a mongoengine.errors.NotUniqueError
error if a document with a duplicate key is passed to the DB. This is not a problem at all since I am able to catch those errors using try-except
.
However, some other documents are something like a bunch of values or parameters. So there is no unique key which a can check in order to prevent those from being inserted to the DB twice. I thought I could read all existing documents from the desired collection like this:
docs = MyCollection.objects()
and check whether the document to be inserted is already available in docs
by using:
doc = MyCollection(parameter='foo')
print(doc in docs)
Which prints false
even if there is a MyCollection(parameter='foo')
document in the the DB already.
How can I achieve a duplicate detection without using unique keys?
Upvotes: 4
Views: 4782
Reputation: 61235
You can check using an if
statement:
if not MyCollection.objects(parameter='foo'):
# insert your documents
Upvotes: 6