Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
How to do bulk insert with ordered false in mongoengine

I'm trying to insert documents in bulk, I have created a unique index in my collection and want to skip documents which are duplicate while doing bulk insertion. This can be accomplished with native mongodb function:

db.collection.insert(
    <document or array of documents>,
    {
        ordered: <boolean>
    }
)

I want to accomplish this with mongoengine, If anybody knows how to achieve this, please answer the question, thanks.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If you have a class like this:

class Foo(db.Document):
    bar= db.StringField()    
    meta = {'indexes': [{'fields': ['bar'], 'unique': True}]}

And having a list with Foo instances foos=[Foo('a'), Foo('a'), Foo('a')] and trying Foo.objects.insert(foos) you will get mongoengine.errors.NotUniqueError

1st woraround would be delete index from mongodb, insert duplicates, and than ensure index with {unique : true, dropDups : true}

2nd workaround would be using underlying pymongo API for bulk ops: https://docs.mongodb.com/manual/reference/method/db.collection.initializeOrderedBulkOp/#db.collection.initializeOrderedBulkOp

over 4 years ago · Santiago Trujillo Report

0

For now I am using raw pymongo from mongoengine as a workaround for this. This is the 2nd workaround that @Alexey Smirnov mentioned. So for a mongoengine Document class DocClass you will access the underlying pymongo collection and execute query like below:

from pymongo.errors import BulkWriteError


try:
    doc_list = [doc.to_mongo() for doc in me_doc_list] # Convert ME objects to what pymongo can understand
    DocClass._get_collection().insert_many(doc_list, ordered=False)

except BulkWriteError as bwe:
    print("Batch Inserted with some errors. May be some duplicates were found and are skipped.")
    print(f"Count is {DocClass.objects.count()}.")

except Exception as e:
    print( { 'error': str(e) })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!