Loading lessons...
Insert Documents
Insert Documents
MongoDB has two methods for inserting documents: insertOne() for a single document, and insertMany() for several at once.
Insert one document
db.posts.insertOne({
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
})
Insert many documents
Pass an array of documents to insertMany():
db.posts.insertMany([
{
title: "Post Title 2",
body: "Body of post.",
category: "Event",
likes: 2,
tags: ["news", "events"],
date: Date()
},
{
title: "Post Title 3",
body: "Body of post.",
category: "Technology",
likes: 3,
tags: ["news", "events"],
date: Date()
}
])
What comes back
insertOne() returns an object with acknowledged and insertedId:
{ acknowledged: true, insertedId: ObjectId("...") }
Shell tips
- After opening an object with
{, press Enter to keep typing on the next line - the command only runs when you press Enter after the closing}. - If the collection doesn't exist, inserting a document creates it automatically.
Note on dates
This tutorial's examples use Date(). In the shell you can also write new Date() or ISODate(...) for a real BSON date value.
TL;DR
insertOne(doc)inserts a single document.insertMany([...])inserts an array of documents.- Missing collections are created automatically on insert.