MongoDB Bulk Insert – MongoDB insertMany

We will look into MongoDB bulk insert today. Multiple documents can be inserted at a time in MongoDB using bulk insert operation where an array of documents is passed to the insert method as parameter.

This operation inserted five documents. MongoDB creates an id field automatically if not specified by the user in the query. The “nInserted” column tells the user number of documents that are inserted.

To view the inserted documents perform the following query as shown below.

In this example, for the second document, the id field is not specified by the user and for the third document only id, name and speed fields are supplied in the query. The query does a successful insertion even though some fields are missing in the second and third documents. The nInserted column says that three documents were inserted.

The documents are inserted and as you can see, it is an unordered insert.
If the insert method encounters an error, the result includes the “WriteResult.writeErrors” field indicating the error message that caused failure.

An unordered list named carbulk is created and insert query is specified with the fields, values to be inserted. Note that it is necessary to call the execute() method following the last insert statement to ensure that the data is actually inserted into the database.

MongoDB Bulk Ordered Insert

This is similar to unordered bulk insert but we use initializeOrderedBulkOp call.

Comments

I am trying to compile your java class MongoDBBulkInsert in my IntelliJ IDEA, in which I have a SBT project, following import are showing red, it means I need to resolve dependency in build.sbt please help me what dependency I need.

Popular Categories

Newsletter for You

Don't miss out!

Subscribe To Newsletter

We promise not to spam you. Unsubscribe at any time.

Invalid email address

Thanks for subscribing!

JournalDev is one of the most popular websites for Java, Python, Android, and related technical articles. Our tutorials are regularly updated, error-free, and complete. Every month millions of developers like you visit JournalDev to read our tutorials.

JournalDev was founded by Pankaj Kumar in 2010 to share his experience and learnings with the whole world. He loves Open source technologies and writing on JournalDev has become his passion.