2

So I understand that MongoDB (and by proxy Mongoose) does not support transactions, but that operations involving a single document are always atomic. In looking over the Mongoose docs, I ran into Model.create which allows one to pass an array of documents and store them in a single action, like so:

var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
 // ...
}

Is this action atomic? Does Mongo save all the documents at once, or does the Mongoose ODM loop through the array, saving one document at a time? Sources (or source code) would be greatly appreciated. (Also, I'm new, so please, don't shoot!)

Community
  • 1
  • 1
MCybertron
  • 123
  • 1
  • 6

1 Answers1

3

MongoDB Wire Protocol accepts either single document or multiple documents with OP_INSERT. However, on the server they are still inserted one at a time.

In other words, if the server were to crash part-way through the insert, some documents would be inserted and others would not be. Within each document you are guaranteed consistent view of it - either it's all inserted or it's not. But for multiple documents no such guarantee exists.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133