Insert operation

The insert operation adds a new document to a collection.

Insert a single document

The insertOne() command is used to add a single document into a collection, using this syntax format:

  1. db.collection.insertOne({field1: value1, field2: value2,.... fieldN: valueN})

The example below depicts how a single document can be added to a collection. If a collection does not exist, the insert command automatically creates one.

  1. db.scientists.insertOne({
  2. name: {
  3. firstname: 'Thomas',
  4. lastname: 'Edison'
  5. },
  6. born: 1847,
  7. invention: 'lightbulb'
  8. })

If the operation is successful, you will get a response with acknowledged set to true, and the autogenerated ObjectId of the document that looks like this:

  1. {
  2. acknowledged: true,
  3. insertedId: ObjectId("6346fcafd7a4a1b0b38eb2db")
  4. }

Insert multiple documents at once

A collection can contain multiple documents. Using the insertMany() command, you can add multiple documents to a collection at once.

  1. db.collection_name.insertMany([{ document1 }, { document2 }, ...{ documentN }])

The following example shows how to insert multiple documents into a collection:

  1. db.scientists.insertMany([
  2. {
  3. name: {
  4. firstname: 'Alan',
  5. lastname: 'Turing'
  6. },
  7. born: 1912,
  8. invention: 'Turing Machine'
  9. },
  10. {
  11. name: {
  12. firstname: 'Graham',
  13. lastname: 'Bell'
  14. },
  15. born: 1847,
  16. invention: 'telephone'
  17. },
  18. {
  19. name: {
  20. firstname: 'Ada',
  21. lastname: 'Lovelace'
  22. },
  23. born: 1815,
  24. invention: 'computer programming'
  25. }
  26. ])

You can retrieve all the documents in the collection with this command: db.scientists.find({})