MongoDB
Beginner
1 min read
Insert Operations
Example
// insertOne — returns { acknowledged: true, insertedId: ObjectId(...) }
const result = await db.collection('users').insertOne({
name: "Carol",
email: "carol@example.com",
age: 28,
createdAt: new Date()
})
console.log('Inserted:', result.insertedId)
// insertMany — bulk insert
const bulk = await db.collection('products').insertMany([
{ name: "Keyboard", price: 79.99, stock: 150 },
{ name: "Mouse", price: 39.99, stock: 200 },
{ name: "Monitor", price: 349.99, stock: 50 }
], { ordered: false }) // continue on error
console.log('Inserted count:', bulk.insertedCount)
console.log('IDs:', bulk.insertedIds)
// Custom _id (must be unique)
await db.collection('config').insertOne({
_id: "appSettings",
theme: "dark",
language: "en"
})