MongoDB CRUD for Documents

Insert, find, update, replace, and delete documents with the core mongosh collection methods.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Create and read
Insert one document
db.products.insertOne({ sku: "A100", name: "Keyboard", price: 49, in_stock: true })

# Create a single document.

Insert many documents
db.products.insertMany([{ sku: "A101", name: "Mouse", price: 19 }, { sku: "A102", name: "Monitor", price: 199 }])

# Create multiple documents in one call.

Find one matching document
db.products.findOne({ sku: "A100" })

# Return a single document by filter.

Find documents with a filter
db.products.find({ in_stock: true, price: { $lt: 100 } })

# Return all matching documents.

Count matching documents
db.products.countDocuments({ in_stock: true })

# Count documents for a specific filter.

## Update and delete
Update one document with $set
db.products.updateOne({ sku: "A100" }, { $set: { price: 59, in_stock: false } })

# Modify selected fields without replacing the whole document.

Update many documents
db.products.updateMany({ category: "accessories" }, { $set: { featured: true } })

# Apply one change to many matching documents.

Replace one document
db.products.replaceOne({ sku: "A101" }, { sku: "A101", name: "Wireless Mouse", price: 29, in_stock: true })

# Swap the entire document body.

Delete one document
db.products.deleteOne({ sku: "A102" })

# Remove the first matching document.

Delete many documents
db.products.deleteMany({ discontinued: true })

# Remove all matching documents.

Upsert a document
db.products.updateOne({ sku: "A103" }, { $set: { name: "Desk Lamp", price: 39 } }, { upsert: true })

# Insert the document if no match exists.

Recommended next

No recommendations yet.