The insertOne method adds a single new document to a MongoDB collection. It helps you save new information in your database.
0
0
insertOne method in MongoDB
Introduction
When you want to add a new user profile to your app's database.
When you need to store a new product in an online store's inventory.
When logging a single event or action in an application.
When saving a new blog post or article to a content database.
When recording a new order in an e-commerce system.
Syntax
MongoDB
db.collection.insertOne(document)db.collection is the collection where you want to add the document.
document is the data object you want to insert.
Examples
Inserts a new user with name Alice and age 30 into the
users collection.MongoDB
db.users.insertOne({ name: "Alice", age: 30 })Adds a new product with a name and price to the
products collection.MongoDB
db.products.insertOne({ productName: "Book", price: 15.99 })Stores a login event with user ID and current time in the
events collection.MongoDB
db.events.insertOne({ eventType: "login", userId: "12345", timestamp: new Date() })Sample Program
This example switches to the myDatabase database and inserts one book document into the books collection.
MongoDB
use myDatabase // Insert a new book document into the books collection db.books.insertOne({ title: "Learn MongoDB", author: "Sam", pages: 200 })
OutputSuccess
Important Notes
The insertOne method returns an object confirming the insert and the new document's ID.
If you insert a document without an _id, MongoDB creates one automatically.
Make sure the document matches your collection's expected structure to avoid confusion later.
Summary
insertOne adds a single document to a MongoDB collection.
It returns confirmation and the new document's unique ID.
Use it when you want to save one new piece of data at a time.