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コマンドは1行のまま表示されます。コピー前に横へスクロールして全体を確認してください。
ローカルで確認しますか?SkillsMP が現在取得できるファイルをダウンロードできます。
Zipをダウンロード ダウンロード中... 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! 🎯
このリポジトリの他の 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 リポジトリを開く