How to Insert Document in MongoDB: Syntax and Examples
To insert a document in MongoDB, use the
insertOne() method on a collection, passing the document as an object. This adds the document to the collection and returns an acknowledgment with the inserted ID.Syntax
The basic syntax to insert a single document into a MongoDB collection is:
db.collection.insertOne(document): Inserts one document into the collection.document: A JSON-like object representing the data to insert.
This method returns an object containing the insertedId of the new document.
mongodb
db.collection.insertOne({ key: "value" })Example
This example shows how to insert a document with a name and age into a users collection.
mongodb
use testdb
db.users.insertOne({ name: "Alice", age: 30 })Output
{ "acknowledged" : true, "insertedId" : ObjectId("someObjectId") }
Common Pitfalls
Common mistakes when inserting documents include:
- Forgetting to use
insertOne()or usinginsert()which is deprecated. - Passing invalid document formats (must be JSON-like objects).
- Not connecting to the correct database or collection before inserting.
Always check the returned acknowledgment to confirm the insert succeeded.
mongodb
/* Wrong: using deprecated insert() */ db.users.insert({ name: "Bob" }) /* Right: use insertOne() */ db.users.insertOne({ name: "Bob" })
Quick Reference
Remember these tips when inserting documents:
- Use
insertOne()for single documents. - Use
insertMany()for multiple documents. - Documents must be valid JSON-like objects.
- Check the insert acknowledgment for success.
Key Takeaways
Use insertOne() to add a single document to a MongoDB collection.
Pass a valid JSON-like object as the document to insert.
Check the returned acknowledgment to confirm successful insertion.
Avoid deprecated methods like insert() for inserting documents.
Ensure you are connected to the correct database and collection before inserting.