Insert

Insert one or several documents into a collection.

Insert documents with insertOne or insertMany. Any node takes the request and sends it to the range that holds each document.

Requirements

  • A connection with a user that has readWrite on the database.

Insert a document

JavaScript
db.orders.insertOne({ customer: "Ana Ruiz", total: 149.5, status: "paid" });

If the document has no _id, the driver gives it an ObjectId before sending it. The response of insertOne gives you that value back in insertedId.

Insert several

JavaScript
db.orders.insertMany(
  [
    { customer: "Luis Gil", total: 32, status: "pending" },
    { customer: "Marta Sanz", total: 75, status: "paid" },
  ],
  { ordered: false },
);

With ordered: false, a document that fails does not stop the others. The response lists every error.

Check

After inserting, db.orders.countDocuments() returns the number of documents of the collection, which has grown by the ones you inserted.

Common problems

  • The insert fails with DuplicateKey (11000) because there is already a document with that _id or with that value in a unique index.
  • The insert fails with DocumentValidationFailure (121) because the document does not meet the collection validator.

See also