Ray Lee
Ray Lee

Reputation: 197

Use insertMany to insert one document in Mongodb

I am confused about why Mongodb needs 2 different methods insertMany and insertOne to insert data. Why just use insertMany? If you want to insert one document, like { a: 1 }, writing like insertMany([{ a: 1 }]) can be exactly same as insertOne({ a: 1 }) functionally, right?

Is there any performance difference between them when just inserting one single document?

Same question about other CRUD functions, any ideas are appreciated! Thanks in advance!

Upvotes: 3

Views: 2579

Answers (1)

twg
twg

Reputation: 1105

If you have multiple documents to insert at once and they are in an array then insertmany() is faster rather than using insertone() over and over for say 500 documents. (Think in terms of a loop in PHP or any other language vs. a one time straight operation).

There are some caveats:

  1. Mongodb limits you to 1000 operations @ once. Notice it is operations not documents. If there a fee e more than 1000 operations Mongodb should split them up. This then of course becomes a function of available memory which can effect a lot of things (pooling) etc.
  2. You must have your documents correctly formatted in an array for insertmany() to work correctly.

The basic same idea applies to all CRUD operations. It is speed but memory (as always with Mongo) is a critical factor.

Upvotes: 2

Related Questions