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 发现并探索由社区构建的 Agent Skills
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-mongodb --skill mongodb-find-queries命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 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! 🎯