Skip to content

Instantly share code, notes, and snippets.

@martinusso
Last active November 3, 2025 19:30
Show Gist options
  • Select an option

  • Save martinusso/1f0251511773e06f4f2eefaa6aac7c77 to your computer and use it in GitHub Desktop.

Select an option

Save martinusso/1f0251511773e06f4f2eefaa6aac7c77 to your computer and use it in GitHub Desktop.
MongoDB, DocumentDB
# 🎯 Basic Navigation
```
// Which database am I using?
db
// List all databases
show dbs
// Switch database
use database_name
// List collections in the current database
show collections
// (Programmatic alternative)
db.getCollectionNames()
```
# 🔢 Counting Documents
```
// Exact count (respects filters)
db.my_collection.countDocuments()
// Fast estimate (approximate)
db.my_collection.estimatedDocumentCount()
// Count with filter
db.my_collection.countDocuments({ status: "ACTIVE" })
```
# 🧾 Quick Listings
```
// First document
db.my_collection.findOne()
// Top 5 documents (pretty formatted)
db.my_collection.find().limit(5).pretty()
// Select specific fields (projection)
db.my_collection.find({}, { _id: 0, name: 1, email: 1 }).limit(5)
```
# ⏱️ Fetch the Latest Document
> “Latest” usually means the document with the **largest `_id`**,
> since `ObjectId` contains an embedded timestamp.
> If your schema has a `createdAt` field, prefer sorting by that.
```
// By _id (most common)
db.my_collection.find().sort({ _id: -1 }).limit(1)
// By createdAt (if available)
db.my_collection.find().sort({ createdAt: -1 }).limit(1)
// Two most recent
db.my_collection.find().sort({ _id: -1 }).limit(2)
```
# 🔎 Field-Based Searches (Useful Filters)
```
// Equality
db.my_collection.find({ status: "ACTIVE" }).limit(10)
// Multiple conditions (implicit AND)
db.my_collection.find({ status: "ACTIVE", type: "PREMIUM" }).limit(10)
// OR condition
db.my_collection.find({ $or: [ { status: "ACTIVE" }, { score: { $gte: 90 } } ] })
// Numeric range
db.my_collection.find({ score: { $gte: 50, $lt: 80 } })
// Partial text (regex, case-insensitive)
db.my_collection.find({ name: { $regex: "smith", $options: "i" } })
// Nested fields / subdocuments
db.my_collection.find({ "address.city": "New York" })
// Date range (ISODate)
db.my_collection.find({
createdAt: {
$gte: ISODate("2025-10-01T00:00:00Z"),
$lt: ISODate("2025-11-01T00:00:00Z")
}
})
// Search by _id
db.my_collection.find({ _id: ObjectId("652f4f9c2b3f4f6c9d31a111") })
```
# 📚 Sorting & Pagination
```
// Sort and paginate
db.my_collection.find({ status: "ACTIVE" })
.sort({ createdAt: -1 })
.skip(20) // skip 20 → page 3 if pageSize = 10
.limit(10) // page size
```
# 🧩 Utilities
```
// Show collection indexes
db.my_collection.getIndexes()
// Collection statistics
db.my_collection.stats()
```
# 🛠️ Copy-and-Use Examples (replace names as needed)
```
// 1) Switch to database and list collections
use merchant_contacts
show collections
// 2) Count all documents in 'contacts'
db.contacts.countDocuments()
// 3) Show the 5 most recent interactions
db.interactions.find().sort({ _id: -1 }).limit(5).pretty()
// 4) Find users with a Gmail address (case-insensitive)
db.users.find({ email: { $regex: "@gmail.com$", $options: "i" } }).limit(10)
// 5) Find events from October 2025
db.events.find({
createdAt: {
$gte: ISODate("2025-10-01T00:00:00Z"),
$lt: ISODate("2025-11-01T00:00:00Z")
}
})
// 6) Show only 'name' and 'phone' fields (hide _id)
db.clients.find({}, { _id: 0, name: 1, phone: 1 }).limit(10)
## another actions
// delete
db.my_collection.drop()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment