MongoDB provides several methods for inserting documents into a collection:
insertOne()
: Inserts a single document into a collection.
Example:
db.users.insertOne({
name: 'John Doe',
age: 30,
email: 'john@example.com'
})
insertMany()
: Inserts multiple documents into a collection.
Example:
db.users.insertMany([
{ name: 'Jane Doe', age: 28, email: 'jane@example.com' },
{ name: 'Bob Smith', age: 35, email: 'bob@example.com' }
])
insert()
: A legacy method that can insert either a single document or multiple documents.
When inserting documents:
_id
field. If not provided, MongoDB generates an ObjectId for this field._id
value, but it must be unique within the collection.Insert operations in MongoDB are atomic at the single-document level.