insertOne and insertMany

insertOne() adds one document to a collection:

db.movies.insertOne({
  _id: 9,
  title: "Oppenheimer",
  director: "Christopher Nolan",
  year: 2023,
  rating: 8.3,
  votes: 2000,
  genres: ["drama", "history"]
})
db.movies.countDocuments()

Output:

{ acknowledged: true, insertedId: 9 }
9

insertOne answers with a short report. acknowledged: true means the server confirmed the write, and insertedId is the _id of the new document. The count shows there are now nine movies.

Each _id can be used only once in a collection. If you insert a document with an _id that is already taken, MongoDB gives a duplicate key error and does not insert it.

To add several documents at once, use insertMany(). It takes an array of documents:

db.movies.insertMany([
  { _id: 10, title: "Arrival", year: 2016 },
  { _id: 11, title: "Sicario", year: 2015 }
])

Output:

{ acknowledged: true, insertedIds: { '0': 10, '1': 11 } }

The report lists each new _id by its place in the array, starting from 0. Notice that these two movies have only three fields. MongoDB did not ask for the missing ones. You decide which fields your documents should have.

If you leave out _id, MongoDB creates one for you:

db.movies.insertOne({ title: "Untitled" })

Output:

{
  acknowledged: true,
  insertedId: ObjectId('6ae5a5e04b36dd3acb7694e8')
}

This value is an ObjectId, an id that MongoDB generates so that it is unique. Yours will be different each time you run this. Real applications usually let MongoDB create ids like this. This course uses small numbers instead, because they are easier to read.

In the exercise, add the movie Tenet with all seven fields.