Seven NoSQL Databases in a Week
上QQ阅读APP看书,第一时间看更新

The create operation

The create operation inserts the new document into the collection. If a collection does not exist, MongoDB will create a new collection and insert a document in it. MongoDB provides the following methods to insert a document into the database:

  • db.collection.insertOne();
  • db.collection.insertMany();

The MongoDB insert operation will target single collections. Also, mongo preserves atomicity at the document level:

This method returns a document that contains the newly added documents _id value:

The method insertMany(), can insert multiple documents into the collection at a time. We have to pass an array of documents to the method:

In MongoDB, each document requires an _id field that uniquely identifies the document that acts as a primary key. If a user does not insert the _id field during the insert operation, MongoDB will automatically generate and insert an ID for each document:

The following is the list of methods that can also be used to insert documents into the collection:

  • db.collection.update();
  • db.collection.updateOne();
  • db.collection.updateMany();
  • db.collection.findAndModify();
  • db.collection.findOneAndUpdate();
  • db.collection.findOneAndReplace();
  • db.collection.save();
  • db.collection.bulkWrite();