CodeStride
Getting Started

Adding documents in NoSQL

Topic 4 of 34 · 9 minFree lesson

So far you've read the bookstore's data. Now it's time to add your own. In MongoDB, you add a document by inserting it: you pass the document to the collection, and MongoDB stores it. There's no table to set up first, and no list of columns to follow.

Adding one document

insertOne adds one document to a collection. You write the document between curly braces, the same way the shell shows them.

Example 1
db.books.insertOne({ title: "The Fifth Season", author: "N. K. Jemisin", year: 2015, price: 11 })
{ acknowledged: true, insertedId: ObjectId('66a0b2c40000000000000001') }

The shell answers with a small report. acknowledged: true means the database received the document. insertedId is the new document's _id.

MongoDB makes the _id for you

You didn't give the new book an _id, so MongoDB made one. Find the book again to see the whole stored document.

Example 2
db.books.insertOne({ title: "Station Eleven", author: "Emily St. John Mandel", year: 2014 })db.books.findOne({ title: "Station Eleven" })
{ acknowledged: true, insertedId: ObjectId('66a0b2c40000000000000001') }{ _id: ObjectId('66a0b2c40000000000000001'), title: 'Station Eleven', author: 'Emily St. John Mandel', year: 2014}

An ObjectId is an id that MongoDB makes, 24 letters and digits long, and no two are the same. Real ones look random. In this course, they're numbered in order, so your results match the lesson.

The new book has no genres, stock or ratings. That's fine: documents in a collection can have different fields.

Choosing your own _id

You can give a document its own _id, like the books' numbers or the authors' short names. MongoDB keeps it instead of making one.

Example 3
db.authors.insertOne({ _id: "morrison", name: "Toni Morrison", born: 1931, country: "United States" })
{ acknowledged: true, insertedId: 'morrison' }

Adding several documents at once

insertMany adds several documents in one command. Put them in square brackets, separated by commas: an array of documents. Then count the books to check that both arrived.

Example 4
db.books.insertMany([ { title: "Homegoing", author: "Yaa Gyasi", year: 2016 }, { title: "Piranesi", author: "Susanna Clarke", year: 2020 }])db.books.countDocuments()
{ acknowledged: true, insertedIds: { '0': ObjectId('66a0b2c40000000000000001'), '1': ObjectId('66a0b2c40000000000000002') }}14

The report lists each new _id by its place in the array, counting from 0. The store had 12 books, and now it has 14.

Inserting into a new collection

The bookstore has no reviews collection yet. You don't need to create one: MongoDB makes a collection the first time you insert into it.

Example 5
db.reviews.insertOne({ bookId: 1, stars: 5, text: "Couldn't put it down." })db.getCollectionNames()
{ acknowledged: true, insertedId: ObjectId('66a0b2c40000000000000001') }[ 'authors', 'books', 'customers', 'orders', 'reviews' ]

reviews now appears next to the other four collections.

Common mistakeReusing an _id that a document already has. Dune's _id is 1, so a second book with _id: 1 is refused, and nothing is added.
Example 6
db.books.insertOne({ _id: 1, title: "Dune Messiah", author: "Frank Herbert" })
MongoServerError: E11000 duplicate key error collection: bookstore.books index: _id_ dup key: { _id: 1 }

E11000 is MongoDB's code for "this value is already taken". The message names the collection and the value that clashed. The index: _id_ part is the rule that keeps each _id unique, and you'll meet indexes later. To fix it, choose an _id nobody has, or leave _id out and let MongoDB make one.

TipLeave _id out unless your data has a natural one, like a short name for each author. The ids MongoDB makes never clash.

Try it yourself

Run the code in the editor and answer 8 practice questions on adding documents. It's free, you only need an account.