npx skills add smithery/pluginagentmarketplace --skill mongodb-find-queries
pluginagentmarketplace/custom-plugin-mongodb · Archived
mongodb-find-queries
Master MongoDB find queries with filters, projections, sorting, and pagination. Learn query operators, comparison, logical operators, and real-world query patterns. Use when retrieving data from MongoDB collections.
Installation
npx skills add pluginagentmarketplace/custom-plugin-mongodb --skill mongodb-find-queries
Stronger alternatives
This repository is archived — consider an actively maintained alternative.
Master MongoDB aggregation pipeline for complex data transformations. Learn pipeline stages, gr…
7 installsMaster MongoDB ACID transactions for multi-document operations. Learn session management, trans…
6 installsMaster MongoDB indexing and query optimization. Learn index types, explain plans, performance t…
5 installsMaster MongoDB security, authentication, authorization, encryption, and backup. Learn role-base…
4 installsSimilar popular skills
Related neighbors and high-traction skills in the same topics — useful to compare before installing.
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill …
1.4K installsPrisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, …
3.6K installsUse when doing ANY task involving Supabase. Triggers: Supabase products (Database, Auth, Edge F…
1.7K installs>- Guides and best practices for working with Lakebase Postgres, the database behind Neon. Cove…
3.2K installs>- Overview of Neon, a complete set of cloud backend primitives for apps and agents, spanning L…
3.2K installsDecision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path …
3.5K installsAlso in this package
Other skills from pluginagentmarketplace/custom-plugin-mongodb · top by installs.
npx skills add pluginagentmarketplace/custom-plugin-mongodb
Browse all from pluginagentmarketplace/custom-plugin-mongodb
More details
Agent compatibility
Declared targets from SKILL.md / docs. Unmarked agents are not listed — the skill may still install via the CLI.
Also listed on
Alternate registries and mirrors of this skill.
Repository health
main
Skill metadata
Parsed from SKILL.md frontmatter.
Package contents
Files included with this skill beyond the listing page.
-
skill md
SKILL.md8,338 B -
docs
SUMMARY.md243 B
History
- First seen on skills.sh
- First recorded snapshot · 3 installs
SKILL.md
MongoDB Find Queries
Master the find() method for powerful data retrieval.
Quick Start
Basic Query
// Find one document
const user = await collection.findOne({ email: '[email protected]' })
// Find multiple documents
const users = await collection.find({ status: 'active' }).toArray()
// Find with multiple conditions
const products = await collection.find({
price: { $gt: 100 },
category: 'electronics'
}).toArray()
Query Operators Reference
Comparison Operators:
{ field: { $eq: value } } // Equal
{ field: { $ne: value } } // Not equal
{ field: { $gt: value } } // Greater than
{ field: { $gte: value } } // Greater or equal
{ field: { $lt: value } } // Less than
{ field: { $lte: value } } // Less or equal
{ field: { $in: [val1, val2] } } // In array
{ field: { $nin: [val1, val2] } } // Not in array
Logical Operators:
{ $and: [{field1: val1}, {field2: val2}] } // AND
{ $or: [{field1: val1}, {field2: val2}] } // OR
{ $not: {field: {$gt: 5}} } // NOT
{ $nor: [{field1: val1}, {field2: val2}] } // NOR
Array Operators:
{ field: { $all: [val1, val2] } } // All values in array
{ field: { $elemMatch: {...} } } // Match array elements
{ field: { $size: 5 } } // Array size exactly 5
Projection (Select Fields)
// Include fields
db.users.findOne({...}, { projection: { name: 1, email: 1 } })
// Returns: { _id, name, email }
// Exclude fields
db.users.findOne({...}, { projection: { password: 0 } })
// Returns: all fields except password
// Hide _id
db.users.findOne({...}, { projection: { _id: 0, name: 1 } })
// Computed fields
db.users.findOne({...}, {
projection: {
firstName: 1,
lastName: 1,
fullName: { $concat: ['$firstName', ' ', '$lastName'] }
}
})
Sorting
// Sort ascending (1) or descending (-1)
db.products.find({}).sort({ price: 1 }).toArray() // Price ascending
db.products.find({}).sort({ createdAt: -1 }).toArray() // Newest first
// Multi-field sort
db.orders.find({}).sort({
status: 1, // Active first
createdAt: -1 // Then newest
}).toArray()
// Case-insensitive sort
db.users.find({}).collation({ locale: 'en', strength: 2 }).sort({ name: 1 })
Pagination
// Method 1: Skip and Limit
const pageSize = 10
const pageNumber = 2
const skip = (pageNumber - 1) * pageSize
const results = await collection
.find({})
.skip(skip)
.limit(pageSize)
.toArray()
// Method 2: Cursor-based (better for large datasets)
const lastId = objectIdOfLastDocument
const results = await collection
.find({ _id: { $gt: lastId } })
.limit(pageSize)
.toArray()
Text Search
// Create text index first
db.articles.createIndex({ title: 'text', content: 'text' })
// Search
db.articles.find(
{ $text: { $search: 'mongodb database' } },
{ score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' } }).toArray()
// Phrase search
db.articles.find({ $text: { $search: '"mongodb database"' } })
// Exclude terms
db.articles.find({ $text: { $search: 'mongodb -relational' } })
Regex Queries
// Case-sensitive regex
db.users.find({ email: { $regex: /^admin/, $options: '' } })
// Case-insensitive
db.users.find({ email: { $regex: /gmail/, $options: 'i' } })
// Multiline
db.posts.find({ content: { $regex: /^mongodb/m } })
// String pattern
db.users.find({ email: { $regex: '^[a-z]+@gmail', $options: 'i' } })
Advanced Query Patterns
Nested Document Queries
// Query nested field
db.users.find({ 'address.city': 'New York' })
// Match entire nested document
db.users.find({ address: { street: '123 Main', city: 'NY' } })
// Nested array
db.orders.find({ 'items.productId': ObjectId(...) })
Date Queries
// Date range
db.orders.find({
createdAt: {
$gte: new Date('2024-01-01'),
$lt: new Date('2024-12-31')
}
})
// This week
const now = new Date()
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
db.posts.find({ publishedAt: { $gte: weekAgo } })
Null Handling
// Find null values
db.users.find({ phone: null })
// Find missing field
db.users.find({ phone: { $exists: false } })
// Find non-null
db.users.find({ phone: { $ne: null } })
// Not missing
db.users.find({ phone: { $exists: true } })
Performance Tips
✅ Query Optimization:
- Use indexes on frequently filtered fields
- Filter early - $match before other stages
- Project fields - Don't fetch unnecessary data
- Limit results - Use pagination
- Use explain() - Analyze every query
✅ Common Mistakes:
- ❌
find({})without limit - Returns all documents - ❌ No index on filtered fields - Full collection scans
- ❌ Fetching fields you don't need - Wastes bandwidth
- ❌ Sorting without index - Memory-intensive
- ❌ Complex regex patterns - Slow performance
Real-World Examples
User Search with Pagination
async function searchUsers(searchTerm, page = 1) {
const pageSize = 20
const skip = (page - 1) * pageSize
const users = await db.users
.find({
$or: [
{ name: { $regex: searchTerm, $options: 'i' } },
{ email: { $regex: searchTerm, $options: 'i' } }
]
})
.project({ password: 0 }) // Don't return passwords
.sort({ name: 1 })
.skip(skip)
.limit(pageSize)
.toArray()
const total = await db.users.countDocuments({
$or: [
{ name: { $regex: searchTerm, $options: 'i' } },
{ email: { $regex: searchTerm, $options: 'i' } }
]
})
return {
data: users,
total,
pages: Math.ceil(total / pageSize),
currentPage: page
}
}
Advanced Filtering
async function filterProducts(filters) {
const query = {}
if (filters.minPrice) query.price = { $gte: filters.minPrice }
if (filters.maxPrice) query.price = { ...query.price, $lte: filters.maxPrice }
if (filters.category) query.category = filters.category
if (filters.inStock) query.stock = { $gt: 0 }
if (filters.rating) query.rating = { $gte: filters.rating }
return await db.products
.find(query)
.sort({ [filters.sortBy]: filters.sortOrder })
.limit(filters.limit || 50)
.toArray()
}
Next Steps
- Create Sample Queries - Find + filters
- Add Projections - Select needed fields
- Implement Sorting - Order results
- Add Pagination - Handle large datasets
- Monitor Performance - Use explain()
You're now a MongoDB query expert! 🎯