Insert Methods - MongoDB

Insert Singe Document

db.collection.insertOne() Inserts a single document into a collection.

Inserting a Document without Specifying an _id Field

db.shop.insertOne({
  "item":"Rice",
  "tags":["food","white"],
  "stock":{
    "quantity":150,
    "uom":"KG"
  }
})

Because the documents did not include _id, mongod creates and adds the _id field and assigns it a unique ObjectId() value.

The ObjectId values are specific to the machine and time when the operation is run.

A Query to view all inserted documents

db.shop.find()

Insert a Document Specifying an _id Field

In the following example, the document passed to the insertOne() method includes the _id field. The value of _id must be unique within the collection to avoid duplicate key error.

db.shop.insertOne({"_id":1,"item":"Sugar"})

Insert Multiple Documents

Insert Several Document without Specifying an _id Field

db.shop.insertMany([
  { _id: 2, item: "Orange" },
  { _id: 3, item: "Pineapple" },
  { _id: 4, item: "banana" }
]);

Inserting an duplicate value for _id throws an exception. The following attempts to insert a document with a _id value that already exists. Since _id : 2 already exists

db.shop.insertMany([
      { _id: 5, item: "Papaya" },
      { _id: 2, item: "Cherry" },
      { _id: 6, item: "Dragon Fruit" },
      { _id: 7, item: "Jackfruit" }
    ]);

Note that one document was inserted: The first document of _id: 5 will insert successfully, but the second insert will fail. This will also stop additional documents left in the queue from being inserted.With ordered to false, the insert operation would continue with any remaining documents.

db.shop.insertMany([
      { _id: 5, item: "Papaya" },
      { _id: 2, item: "Cherry" },
      { _id: 6, item: "Dragon Fruit"},
      { _id: 7, item: "Jackfruit" }
    ],{ordered:false});