Insert Operations
Now that you understand databases and collections, it is time to add some data! In MongoDB, we insert documents into collections. MongoDB provides two main methods: insertOne() for single documents and insertMany() for multiple documents.
What is a Document?
A document is a set of key-value pairs, similar to JSON objects. Documents are the basic unit of data in MongoDB.
{ "_id": ObjectId("65a1b2c3d4e5f6a7b8c9d0e1"), "name": "John Doe", "email": "john@example.com", "age": 30, "hobbies": ["reading", "gaming"]}Think of a document as a digital index card. You can write anything you want on it – name, age, hobbies – and you can store many cards in a box (collection).
The _id Field
Every document in MongoDB must have an _id field. If you don't provide one, MongoDB automatically creates an ObjectId for you. This field is unique within a collection.
Insert One Document (insertOne)
<!-- Switch to your database -->use myblog
<!-- Insert a single document -->db.posts.insertOne({ title: "First Post", content: "This is my first blog post!", author: "John", tags: ["mongodb", "nodejs"], createdAt: new Date()})Output:
{ acknowledged: true, insertedId: ObjectId("65a1b2c3d4e5f6a7b8c9d0e1")}Insert Multiple Documents (insertMany)
db.posts.insertMany([ { title: "Second Post", content: "Learning MongoDB is fun!", author: "John", tags: ["mongodb", "database"] }, { title: "Third Post", content: "Node.js and MongoDB are great together!", author: "Jane", tags: ["nodejs", "express"] }])Output:
{ acknowledged: true, insertedIds: { '0': ObjectId("65a1b2c3d4e5f6a7b8c9d0e2"), '1': ObjectId("65a1b2c3d4e5f6a7b8c9d0e3") }}Insert with Custom _id
You can provide your own _id value:
db.users.insertOne({ _id: "user123", name: "Alice", email: "alice@example.com"})Insert with Different Fields
Remember: MongoDB does not enforce a schema. Documents in the same collection can have different fields!
db.users.insertMany([ { name: "Bob", age: 25 }, { name: "Charlie", email: "charlie@example.com" }, { username: "david", phone: "123-456-7890" }])Check Your Inserts
To see all documents in a collection:
db.posts.find()db.users.find()Two Minute Drill
- Use insertOne() to add a single document to a collection.
- Use insertMany() to add multiple documents at once.
- MongoDB automatically adds an _id field if you do not provide one.
- Documents in the same collection can have different fields – flexible schema!
- Always check the return value to confirm successful insertion.
Need more clarification?
Drop us an email at career@quipoinfotech.com
