Unable to Insert if one Doc exist in insertMany()

Annotation%202019-09-23%20132008 Annotation%202019-09-23%20132242

Tried to insert as per the lesson and it did not do so.
I already had the title:Star Trek II: The Wrath of Khan and when I insert the following I get 0 inserts when it should have been 3 inserts. Kindly help understand.

db.moviesScratch.insertMany(
	[
		{
		"_id": "tt0084726",
		"title":"Star Trek II: The Wrath of Khan",
		"year": 1982,
		"type": "movie"
		},
		{
		"_id": "tt0796366",
		"title":"Star Trek",
		"year": 2009,
		"type": "movie"
		},
		{
		"_id": "tt0084726",
		"title":"Star Trek II: The Wrath of Khan",
		"year": 1982,
		"type": "movie"
		},
		{
		"_id": "tt1408101",
		"title":"Star Trek Into Darkness",
		"year": 2013,
		"type": "movie"
		},
		{
		"_id": "tt0117731",
		"title":"Star Trek: First Contact",
		"year": 1996,
		"type": "movie"
		}
	]
)

Hi @jerrin-jacob,

In MongoDB you cannot have two documents with the same value for _id field. In this InsertMany() operation that you are performing, the first and the third documents have the same _id field i.e. "_id": "tt0084726".

So when you execute this query, the first and the second documents get inserted fine as they have unique _id field. However, the third document cannot get inserted because there is already one document in the collection with the same _id field.

Now for the insertMany() function there is an additional parameter called ordered. If this field is set to true then this function inserts the document in an ordered fashion which means it stops inserting documenting as soon as it encounter an error. However, if you set this field to false then it keeps on inserting the document by skipping those which throws an error.

If you watch the video Lecture: Creating Documents: insertMany() somewhere around 4:20, it has been discussed.

Hope it helps.

Happy Learning :slight_smile:

Thanks,
Shubham Ranjan
Curriculum Support Engineer