0
0
MongodbHow-ToBeginner · 3 min read

How to Use insertOne in MongoDB: Simple Guide

Use insertOne() in MongoDB to add a single document to a collection. It takes the document as an argument and returns a result with the inserted document's ID.
📐

Syntax

The insertOne() method is called on a MongoDB collection to add one document. It takes one argument: the document object you want to insert. It returns a promise that resolves with an object containing the inserted document's ID.

  • collection.insertOne(document): Inserts document into the collection.
  • document: A JavaScript object representing the data to store.
  • The method returns an object with insertedId showing the new document's unique ID.
javascript
db.collection('users').insertOne({ name: 'Alice', age: 25 })
💻

Example

This example shows how to connect to a MongoDB database, insert one document into the users collection, and print the inserted document's ID.

javascript
const { MongoClient } = require('mongodb');

async function run() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const database = client.db('testdb');
    const users = database.collection('users');

    const userDoc = { name: 'Alice', age: 25 };
    const result = await users.insertOne(userDoc);

    console.log('Inserted document ID:', result.insertedId);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Inserted document ID: ObjectId("<some_object_id>")
⚠️

Common Pitfalls

Common mistakes when using insertOne() include:

  • Passing an array instead of a single document (use insertMany() for multiple documents).
  • Not awaiting the promise in async code, causing unexpected behavior.
  • Inserting documents without required fields if your schema expects them.

Always ensure your document is a plain object and handle the promise correctly.

javascript
/* Wrong: inserting an array with insertOne */
db.collection('users').insertOne([{ name: 'Bob' }, { name: 'Carol' }]);

/* Right: insertOne with a single document */
db.collection('users').insertOne({ name: 'Bob' });
📊

Quick Reference

MethodDescriptionArgumentReturns
insertOne(document)Insert one document into collectionA single document objectPromise resolving to an object with insertedId

Key Takeaways

Use insertOne() to add a single document to a MongoDB collection.
Pass a plain object as the document argument to insertOne().
Always await insertOne() in async code to get the inserted document ID.
Use insertMany() if you want to insert multiple documents at once.
Check for required fields before inserting to avoid schema errors.