Skip to main content 홈 크리에이터 pluginagentmarketplace custom-plugin-mongodb mongodb-find-queries
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.
설치로 이동 Skills Marketplace 커뮤니티가 만든 AI 스킬을 발견하고 탐색하세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-mongodb --skill mongodb-find-queries명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
Zip 다운로드 다운로드 중... 이 저장소의 다른 Skills mongodb-aggregation-pipeline Master MongoDB aggregation pipeline for complex data transformations. Learn pipeline stages, grouping, filtering, and data transformation. Use when analyzing data, creating reports, or transforming documents.
Master MongoDB Atlas cloud setup, cluster configuration, security, networking, backups, and monitoring. Get production-ready cloud database in minutes. Use when setting up cloud MongoDB, configuring clusters, or managing Atlas.
Master MongoDB authentication methods including SCRAM, X.509 certificates, LDAP, and Kerberos. Learn user creation, role assignment, and securing MongoDB deployments.
pluginagentmarketplace
pluginagentmarketplace/custom-plugin-mongodb
GitHub 저장소 열기 name mongodb-find-queries version 2.1.0 description 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. sasmp_version 1.3.0 bonded_agent 02-mongodb-queries-aggregation bond_type PRIMARY_BOND capabilities ["query-construction","filter-operators","projection-design","sorting-pagination","text-search"] input_validation {"required_context":["collection_name","filter_criteria"],"optional_context":["projection_fields","sort_order","pagination_params"]} output_format {"query":"object","options":"object","explanation":"string","performance_tips":"array"} error_handling {"common_errors":[{"code":"FIND001","condition":"Projection mixing include/exclude","recovery":"Use either inclusion or exclusion, not both (except _id)"},{"code":"FIND002","condition":"Sort memory limit exceeded","recovery":"Create index on sort field or use allowDiskUse"},{"code":"FIND003","condition":"Invalid regex pattern","recovery":"Validate regex syntax, escape special characters"}]} prerequisites {"mongodb_version":"4.0+","required_knowledge":["mongodb-basics","query-operators"],"index_requirements":["Indexes on frequently filtered fields recommended"]} testing {"unit_test_template":"// Test find query\nconst results = await collection.find(filter, { projection }).toArray()\nexpect(results).toHaveLength(expectedCount)\nexpect(results[0]).toHaveProperty('expectedField')\n"}
MongoDB Find Queries
Master the find() method for powerful data retrieval.
Quick Start
Basic Query
const user = await collection.findOne ({ email : 'user@example.com' })
const users = await collection.find ({ status : 'active' }).toArray ()
const products = await collection.find ({
price : { $gt : 100 },
category : 'electronics'
}).toArray ()
Query Operators Reference
Comparison Operators:
{ field : { $eq : value } }
{ field : { $ne : value } }
{ field : { $gt : value } }
{ field : { $gte : value } }
{ field : { $lt : value } }
{ field : { $lte : value } }
{ field : { $in : [val1, val2] } }
{ field : { : [val1, val2] } }
$nin
{ $and : [{field1 : val1}, {field2 : val2}] }
{ $or : [{field1 : val1}, {field2 : val2}] }
{ $not : {field : {$gt : 5 }} }
{ $nor : [{field1 : val1}, {field2 : val2}] }
{ field : { $all : [val1, val2] } }
{ field : { $elemMatch : {...} } }
{ field : { $size : 5 } }
Projection (Select Fields)
db.users .findOne ({...}, { projection : { name : 1 , email : 1 } })
db.users .findOne ({...}, { projection : { password : 0 } })
db.users .findOne ({...}, { projection : { _id : 0 , name : 1 } })
db.users .findOne ({...}, {
projection : {
firstName : 1 ,
lastName : 1 ,
fullName : { $concat : ['$firstName' , ' ' , '$lastName' ] }
}
})
Sorting
db.products .find ({}).sort ({ price : 1 }).toArray ()
db.products .find ({}).sort ({ createdAt : -1 }).toArray ()
db.orders .find ({}).sort ({
status : 1 ,
createdAt : -1
}).toArray ()
db.users .find ({}).collation ({ locale : 'en' , strength : 2 }).sort ({ name : 1 })
Pagination
const pageSize = 10
const pageNumber = 2
const skip = (pageNumber - 1 ) * pageSize
const results = await collection
.find ({})
.skip (skip)
.limit (pageSize)
.toArray ()
const lastId = objectIdOfLastDocument
const results = await collection
.find ({ _id : { $gt : lastId } })
.limit (pageSize)
.toArray ()
Text Search
db.articles .createIndex ({ title : 'text' , content : 'text' })
db.articles .find (
{ $text : { $search : 'mongodb database' } },
{ score : { $meta : 'textScore' } }
).sort ({ score : { $meta : 'textScore' } }).toArray ()
db.articles .find ({ $text : { $search : '"mongodb database"' } })
db.articles .find ({ $text : { $search : 'mongodb -relational' } })
Regex Queries
db.users .find ({ email : { $regex : /^admin/ , $options : '' } })
db.users .find ({ email : { $regex : /gmail/ , $options : 'i' } })
db.posts .find ({ content : { $regex : /^mongodb/m } })
db.users .find ({ email : { $regex : '^[a-z]+@gmail' , $options : 'i' } })
Advanced Query Patterns
Nested Document Queries
db.users .find ({ 'address.city' : 'New York' })
db.users .find ({ address : { street : '123 Main' , city : 'NY' } })
db.orders .find ({ 'items.productId' : ObjectId (...) })
Date Queries
db.orders .find ({
createdAt : {
$gte : new Date ('2024-01-01' ),
$lt : new Date ('2024-12-31' )
}
})
const now = new Date ()
const weekAgo = new Date (now.getTime () - 7 * 24 * 60 * 60 * 1000 )
db.posts .find ({ publishedAt : { $gte : weekAgo } })
Null Handling
db.users .find ({ phone : null })
db.users .find ({ phone : { $exists : false } })
db.users .find ({ phone : { $ne : null } })
db.users .find ({ phone : { $exists : true } })
Performance Tips
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
❌ 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 })
.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! 🎯