[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M733K3WK1RY3WX32H5G02A82":3,"skill-same:01M733K3WK1RY3WX32H5G02A82":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":14,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M733K3WK1RY3WX32H5G02A82","mongodb",null,"MongoDB - NoSQL document database with flexible schema design, aggregation pipelines, indexing strategies, and Spring Data integration","julio211916\u002FTlantiCAD-Studio-V0.1-alpha","julio211916","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128201165?v=4","01M730ENY015MHFY82VKR6AGGR","José Carlos amador garcia","01M730ENYT83EWH6EXRHF9FTXV",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fmongodb\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: mongodb\ndescription: MongoDB - NoSQL document database with flexible schema design, aggregation pipelines, indexing strategies, and Spring Data integration\nversion: 1.0.0\ncategory: toolchain\nauthor: Claude MPM Team\nlicense: MIT\nprogressive_disclosure:\n  entry_point:\n    summary: \"Document-oriented NoSQL database with flexible schemas, powerful aggregation framework, horizontal scaling, and rich query language\"\n    when_to_use: \"Building apps with flexible\u002Fevolving schemas, hierarchical data, real-time analytics, geospatial queries, or need horizontal scaling\"\n    quick_start: \"1. Design documents (embedded vs referenced) 2. Create indexes for queries 3. Use aggregation for analytics 4. Implement proper connection pooling\"\ncontext_limit: 700\ntags:\n  - mongodb\n  - nosql\n  - database\n  - document-database\n  - aggregation\n  - indexing\n  - spring-data\n  - schema-design\nrequires_tools: []\n---\n\n# MongoDB - Document Database Patterns\n\n## Overview\n\nMongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents. It excels at handling unstructured or semi-structured data, hierarchical relationships, and scenarios requiring horizontal scaling.\n\n**Key Features**:\n- Flexible schema (schemaless documents)\n- Rich query language with secondary indexes\n- Aggregation framework for analytics\n- Horizontal scaling (sharding)\n- Replica sets for high availability\n- Change streams for real-time data\n- Geospatial and full-text search\n\n**When to Use MongoDB**:\n- Rapidly evolving schemas\n- Hierarchical\u002Fnested data (embedded documents)\n- Real-time analytics with aggregation\n- Geospatial applications\n- Content management systems\n- IoT data ingestion\n- Catalog\u002Finventory systems\n\n**When NOT to Use MongoDB**:\n- Complex multi-table joins (use RDBMS)\n- ACID transactions across many documents (improved in 4.0+, but limited)\n- Strict schema enforcement requirements\n\n## Schema Design Fundamentals\n\n### Document Structure\n\n```javascript\n\u002F\u002F MongoDB document (BSON format)\n{\n  \"_id\": ObjectId(\"507f1f77bcf86cd799439011\"),  \u002F\u002F Primary key (auto-generated)\n  \"email\": \"alice@example.com\",\n  \"name\": \"Alice Johnson\",\n  \"profile\": {                                   \u002F\u002F Embedded document\n    \"bio\": \"Software developer\",\n    \"avatar\": \"https:\u002F\u002Fexample.com\u002Favatar.jpg\",\n    \"social\": {\n      \"twitter\": \"@alice\",\n      \"github\": \"alice-dev\"\n    }\n  },\n  \"tags\": [\"developer\", \"python\", \"mongodb\"],    \u002F\u002F Array field\n  \"createdAt\": ISODate(\"2024-01-15T10:30:00Z\"),\n  \"updatedAt\": ISODate(\"2024-01-20T14:22:00Z\")\n}\n```\n\n### Embedded vs Referenced Documents\n\n**Embedded (Denormalized)** - Store related data in same document:\n\n```javascript\n\u002F\u002F Embedded: Good for 1:1 or 1:Few relationships\n\u002F\u002F User with embedded address\n{\n  \"_id\": ObjectId(\"...\"),\n  \"name\": \"Alice\",\n  \"address\": {\n    \"street\": \"123 Main St\",\n    \"city\": \"San Francisco\",\n    \"zipCode\": \"94102\"\n  }\n}\n\n\u002F\u002F Embedded: Order with line items (1:Many bounded)\n{\n  \"_id\": ObjectId(\"...\"),\n  \"orderNumber\": \"ORD-2024-001\",\n  \"customer\": { \"name\": \"Alice\", \"email\": \"alice@example.com\" },\n  \"items\": [\n    { \"productId\": \"SKU001\", \"name\": \"Widget\", \"quantity\": 2, \"price\": 29.99 },\n    { \"productId\": \"SKU002\", \"name\": \"Gadget\", \"quantity\": 1, \"price\": 49.99 }\n  ],\n  \"total\": 109.97\n}\n```\n\n**When to Embed**:\n- Data is queried together frequently\n- Child data doesn't make sense without parent\n- 1:1 or 1:Few relationships\n- Child data is bounded (won't grow unbounded)\n- Data doesn't need to be accessed independently\n\n**Referenced (Normalized)** - Store references to other documents:\n\n```javascript\n\u002F\u002F Referenced: Good for 1:Many unbounded or Many:Many\n\u002F\u002F User document\n{\n  \"_id\": ObjectId(\"user123\"),\n  \"name\": \"Alice\",\n  \"email\": \"alice@example.com\"\n}\n\n\u002F\u002F Posts collection (references user)\n{\n  \"_id\": ObjectId(\"post456\"),\n  \"authorId\": ObjectId(\"user123\"),   \u002F\u002F Reference to user\n  \"title\": \"MongoDB Schema Design\",\n  \"content\": \"...\",\n  \"commentCount\": 42\n}\n\n\u002F\u002F Comments collection (references post)\n{\n  \"_id\": ObjectId(\"comment789\"),\n  \"postId\": ObjectId(\"post456\"),     \u002F\u002F Reference to post\n  \"authorId\": ObjectId(\"user999\"),   \u002F\u002F Reference to commenter\n  \"text\": \"Great article!\",\n  \"createdAt\": ISODate(\"2024-01-20T10:00:00Z\")\n}\n```\n\n**When to Reference**:\n- Many:Many relationships\n- 1:Many with unbounded growth (comments, logs)\n- Data is accessed independently\n- Document size would exceed 16MB limit\n- Need atomic updates on referenced document\n\n### Hybrid Pattern (Extended Reference)\n\n```javascript\n\u002F\u002F Post with denormalized author info + reference\n{\n  \"_id\": ObjectId(\"post456\"),\n  \"title\": \"MongoDB Best Practices\",\n  \"content\": \"...\",\n  \"author\": {\n    \"_id\": ObjectId(\"user123\"),      \u002F\u002F Reference for lookups\n    \"name\": \"Alice\",                 \u002F\u002F Denormalized for display\n    \"avatar\": \"https:\u002F\u002F...\"          \u002F\u002F Frequently needed fields\n  },\n  \"commentCount\": 42,\n  \"lastCommentAt\": ISODate(\"...\")\n}\n```\n\n## Query Patterns\n\n### Basic CRUD Operations\n\n```javascript\n\u002F\u002F Find documents\ndb.users.find({ email: \"alice@example.com\" })\ndb.users.find({ age: { $gte: 18, $lte: 65 } })\ndb.users.find({ tags: { $in: [\"developer\", \"designer\"] } })\n\n\u002F\u002F Find with projection (select specific fields)\ndb.users.find(\n  { status: \"active\" },\n  { name: 1, email: 1, _id: 0 }  \u002F\u002F Include name, email; exclude _id\n)\n\n\u002F\u002F Find one\ndb.users.findOne({ email: \"alice@example.com\" })\n\n\u002F\u002F Insert\ndb.users.insertOne({ name: \"Bob\", email: \"bob@example.com\" })\ndb.users.insertMany([\n  { name: \"Charlie\", email: \"charlie@example.com\" },\n  { name: \"Diana\", email: \"diana@example.com\" }\n])\n\n\u002F\u002F Update\ndb.users.updateOne(\n  { email: \"alice@example.com\" },\n  { $set: { name: \"Alice Updated\", updatedAt: new Date() } }\n)\n\ndb.users.updateMany(\n  { status: \"inactive\" },\n  { $set: { archived: true } }\n)\n\n\u002F\u002F Upsert (update or insert)\ndb.users.updateOne(\n  { email: \"new@example.com\" },\n  { $set: { name: \"New User\", createdAt: new Date() } },\n  { upsert: true }\n)\n\n\u002F\u002F Delete\ndb.users.deleteOne({ email: \"bob@example.com\" })\ndb.users.deleteMany({ status: \"deleted\" })\n```\n\n### Query Operators\n\n```javascript\n\u002F\u002F Comparison\ndb.products.find({ price: { $gt: 100 } })        \u002F\u002F Greater than\ndb.products.find({ price: { $gte: 100 } })       \u002F\u002F Greater than or equal\ndb.products.find({ price: { $lt: 50 } })         \u002F\u002F Less than\ndb.products.find({ price: { $lte: 50 } })        \u002F\u002F Less than or equal\ndb.products.find({ price: { $ne: 0 } })          \u002F\u002F Not equal\ndb.products.find({ category: { $in: [\"A\", \"B\"] } })   \u002F\u002F In array\ndb.products.find({ category: { $nin: [\"C\", \"D\"] } })  \u002F\u002F Not in array\n\n\u002F\u002F Logical\ndb.users.find({ $and: [{ age: { $gte: 18 } }, { status: \"active\" }] })\ndb.users.find({ $or: [{ role: \"admin\" }, { role: \"moderator\" }] })\ndb.users.find({ age: { $not: { $lt: 18 } } })\n\n\u002F\u002F Element\ndb.users.find({ middleName: { $exists: true } })  \u002F\u002F Field exists\ndb.users.find({ age: { $type: \"number\" } })       \u002F\u002F Field type\n\n\u002F\u002F Array\ndb.posts.find({ tags: \"mongodb\" })                \u002F\u002F Contains element\ndb.posts.find({ tags: { $all: [\"mongodb\", \"database\"] } })  \u002F\u002F Contains all\ndb.posts.find({ tags: { $size: 3 } })             \u002F\u002F Array size\ndb.posts.find({ \"tags.0\": \"featured\" })           \u002F\u002F First element\n\n\u002F\u002F Embedded documents\ndb.users.find({ \"address.city\": \"San Francisco\" })\ndb.users.find({ \"profile.social.twitter\": { $exists: true } })\n\n\u002F\u002F Regex\ndb.users.find({ name: { $regex: \u002F^alice\u002Fi } })\ndb.users.find({ email: { $regex: \u002F@example\\.com$\u002F } })\n```\n\n### Update Operators\n\n```javascript\n\u002F\u002F Field updates\ndb.users.updateOne(\n  { _id: userId },\n  {\n    $set: { name: \"New Name\" },           \u002F\u002F Set field value\n    $unset: { temporaryField: \"\" },       \u002F\u002F Remove field\n    $rename: { oldName: \"newName\" },      \u002F\u002F Rename field\n    $inc: { loginCount: 1 },              \u002F\u002F Increment\n    $mul: { price: 1.1 },                 \u002F\u002F Multiply\n    $min: { lowestScore: 50 },            \u002F\u002F Set if less than current\n    $max: { highestScore: 100 },          \u002F\u002F Set if greater than current\n    $currentDate: { updatedAt: true }     \u002F\u002F Set to current date\n  }\n)\n\n\u002F\u002F Array updates\ndb.posts.updateOne(\n  { _id: postId },\n  {\n    $push: { tags: \"new-tag\" },           \u002F\u002F Add to array\n    $addToSet: { tags: \"unique-tag\" },    \u002F\u002F Add if not exists\n    $pop: { tags: 1 },                    \u002F\u002F Remove last (-1 for first)\n    $pull: { tags: \"old-tag\" },           \u002F\u002F Remove specific value\n    $pullAll: { tags: [\"a\", \"b\"] }        \u002F\u002F Remove multiple values\n  }\n)\n\n\u002F\u002F Array with modifiers\ndb.posts.updateOne(\n  { _id: postId },\n  {\n    $push: {\n      comments: {\n        $each: [comment1, comment2],      \u002F\u002F Add multiple\n        $sort: { createdAt: -1 },         \u002F\u002F Sort after push\n        $slice: -100                      \u002F\u002F Keep only last 100\n      }\n    }\n  }\n)\n\n\u002F\u002F Positional update (update matched array element)\ndb.posts.updateOne(\n  { _id: postId, \"comments._id\": commentId },\n  { $set: { \"comments.$.text\": \"Updated comment\" } }\n)\n\n\u002F\u002F Update all matching array elements\ndb.posts.updateOne(\n  { _id: postId },\n  { $set: { \"comments.$[elem].read\": true } },\n  { arrayFilters: [{ \"elem.userId\": currentUserId }] }\n)\n```\n\n## Indexing Strategies\n\n### Index Types\n\n```javascript\n\u002F\u002F Single field index\ndb.users.createIndex({ email: 1 })         \u002F\u002F Ascending\ndb.users.createIndex({ createdAt: -1 })    \u002F\u002F Descending\n\n\u002F\u002F Compound index\ndb.orders.createIndex({ customerId: 1, createdAt: -1 })\n\n\u002F\u002F Unique index\ndb.users.createIndex({ email: 1 }, { unique: true })\n\n\u002F\u002F Partial index (index subset of documents)\ndb.orders.createIndex(\n  { createdAt: 1 },\n  { partialFilterExpression: { status: \"pending\" } }\n)\n\n\u002F\u002F TTL index (auto-delete old documents)\ndb.sessions.createIndex(\n  { createdAt: 1 },\n  { expireAfterSeconds: 3600 }  \u002F\u002F Delete after 1 hour\n)\n\n\u002F\u002F Text index (full-text search)\ndb.articles.createIndex({ title: \"text\", content: \"text\" })\n\u002F\u002F Query: db.articles.find({ $text: { $search: \"mongodb tutorial\" } })\n\n\u002F\u002F Geospatial index\ndb.locations.createIndex({ coordinates: \"2dsphere\" })\n\u002F\u002F Query: db.locations.find({\n\u002F\u002F   coordinates: {\n\u002F\u002F     $near: {\n\u002F\u002F       $geometry: { type: \"Point\", coordinates: [-122.4, 37.8] },\n\u002F\u002F       $maxDistance: 5000  \u002F\u002F meters\n\u002F\u002F     }\n\u002F\u002F   }\n\u002F\u002F })\n\n\u002F\u002F Multikey index (for array fields - automatic)\ndb.posts.createIndex({ tags: 1 })\n\n\u002F\u002F Hashed index (for sharding)\ndb.users.createIndex({ email: \"hashed\" })\n```\n\n### Index Best Practices\n\n```javascript\n\u002F\u002F ESR Rule for compound indexes: Equality, Sort, Range\n\u002F\u002F Query: find users where status = \"active\", sorted by createdAt, age > 18\n\u002F\u002F Index: { status: 1, createdAt: -1, age: 1 }\n\u002F\u002F        ^Equality   ^Sort          ^Range\n\n\u002F\u002F Covered queries (all fields in index)\ndb.users.createIndex({ email: 1, name: 1, status: 1 })\ndb.users.find(\n  { email: \"alice@example.com\" },\n  { name: 1, status: 1, _id: 0 }  \u002F\u002F All fields from index\n)\n\u002F\u002F Check with explain: \"totalDocsExamined\": 0\n\n\u002F\u002F Analyze query performance\ndb.users.find({ email: \"alice@example.com\" }).explain(\"executionStats\")\n\u002F\u002F Look for:\n\u002F\u002F - IXSCAN (index scan) vs COLLSCAN (collection scan)\n\u002F\u002F - totalDocsExamined vs totalKeysExamined\n\u002F\u002F - executionTimeMillis\n\n\u002F\u002F List indexes\ndb.users.getIndexes()\n\n\u002F\u002F Drop index\ndb.users.dropIndex(\"email_1\")\ndb.users.dropIndex({ email: 1, name: 1 })\n```\n\n## Aggregation Pipeline\n\n### Pipeline Stages\n\n```javascript\n\u002F\u002F Basic aggregation structure\ndb.orders.aggregate([\n  { $match: { status: \"completed\" } },           \u002F\u002F Filter (like WHERE)\n  { $group: { _id: \"$customerId\", total: { $sum: \"$amount\" } } },  \u002F\u002F Group\n  { $sort: { total: -1 } },                      \u002F\u002F Sort\n  { $limit: 10 }                                 \u002F\u002F Limit results\n])\n\n\u002F\u002F Common stages\ndb.collection.aggregate([\n  \u002F\u002F $match - Filter documents\n  { $match: { status: \"active\", createdAt: { $gte: ISODate(\"2024-01-01\") } } },\n\n  \u002F\u002F $project - Reshape documents (include\u002Fexclude\u002Fcompute fields)\n  { $project: {\n    name: 1,\n    email: 1,\n    fullName: { $concat: [\"$firstName\", \" \", \"$lastName\"] },\n    yearCreated: { $year: \"$createdAt\" }\n  }},\n\n  \u002F\u002F $addFields - Add new fields (keeps existing)\n  { $addFields: {\n    totalPrice: { $multiply: [\"$price\", \"$quantity\"] }\n  }},\n\n  \u002F\u002F $group - Group and aggregate\n  { $group: {\n    _id: \"$category\",\n    count: { $sum: 1 },\n    totalRevenue: { $sum: \"$amount\" },\n    avgPrice: { $avg: \"$price\" },\n    maxPrice: { $max: \"$price\" },\n    products: { $push: \"$name\" },          \u002F\u002F Collect into array\n    uniqueTags: { $addToSet: \"$tag\" }      \u002F\u002F Unique values\n  }},\n\n  \u002F\u002F $sort\n  { $sort: { totalRevenue: -1, count: 1 } },\n\n  \u002F\u002F $skip and $limit (pagination)\n  { $skip: 20 },\n  { $limit: 10 },\n\n  \u002F\u002F $unwind - Deconstruct array field\n  { $unwind: \"$tags\" },\n  \u002F\u002F { tags: [\"a\", \"b\"] } becomes { tags: \"a\" }, { tags: \"b\" }\n\n  \u002F\u002F $lookup - Join collections\n  { $lookup: {\n    from: \"users\",\n    localField: \"authorId\",\n    foreignField: \"_id\",\n    as: \"author\"\n  }},\n  { $unwind: \"$author\" },  \u002F\u002F Convert single-element array to object\n\n  \u002F\u002F $facet - Multiple pipelines in parallel\n  { $facet: {\n    results: [{ $skip: 0 }, { $limit: 10 }],\n    totalCount: [{ $count: \"count\" }]\n  }}\n])\n```\n\n### Real-World Aggregation Examples\n\n```javascript\n\u002F\u002F Sales analytics by month\ndb.orders.aggregate([\n  { $match: { status: \"completed\" } },\n  { $group: {\n    _id: {\n      year: { $year: \"$createdAt\" },\n      month: { $month: \"$createdAt\" }\n    },\n    totalSales: { $sum: \"$amount\" },\n    orderCount: { $sum: 1 },\n    avgOrderValue: { $avg: \"$amount\" }\n  }},\n  { $sort: { \"_id.year\": -1, \"_id.month\": -1 } }\n])\n\n\u002F\u002F Top customers with order details\ndb.orders.aggregate([\n  { $match: { createdAt: { $gte: ISODate(\"2024-01-01\") } } },\n  { $group: {\n    _id: \"$customerId\",\n    totalSpent: { $sum: \"$amount\" },\n    orderCount: { $sum: 1 },\n    lastOrder: { $max: \"$createdAt\" }\n  }},\n  { $sort: { totalSpent: -1 } },\n  { $limit: 10 },\n  { $lookup: {\n    from: \"customers\",\n    localField: \"_id\",\n    foreignField: \"_id\",\n    as: \"customer\"\n  }},\n  { $unwind: \"$customer\" },\n  { $project: {\n    customerName: \"$customer.name\",\n    customerEmail: \"$customer.email\",\n    totalSpent: 1,\n    orderCount: 1,\n    lastOrder: 1\n  }}\n])\n\n\u002F\u002F Product category performance with nested unwind\ndb.orders.aggregate([\n  { $unwind: \"$items\" },\n  { $lookup: {\n    from: \"products\",\n    localField: \"items.productId\",\n    foreignField: \"_id\",\n    as: \"product\"\n  }},\n  { $unwind: \"$product\" },\n  { $group: {\n    _id: \"$product.category\",\n    totalRevenue: { $sum: { $multiply: [\"$items.quantity\", \"$items.price\"] } },\n    unitsSold: { $sum: \"$items.quantity\" },\n    uniqueProducts: { $addToSet: \"$product._id\" }\n  }},\n  { $addFields: {\n    uniqueProductCount: { $size: \"$uniqueProducts\" }\n  }},\n  { $sort: { totalRevenue: -1 } }\n])\n```\n\n## Transactions (MongoDB 4.0+)\n\n```javascript\n\u002F\u002F Multi-document transaction\nconst session = client.startSession();\n\ntry {\n  session.startTransaction();\n\n  \u002F\u002F Transfer money between accounts\n  await accounts.updateOne(\n    { _id: fromAccountId },\n    { $inc: { balance: -amount } },\n    { session }\n  );\n\n  await accounts.updateOne(\n    { _id: toAccountId },\n    { $inc: { balance: amount } },\n    { session }\n  );\n\n  await transactions.insertOne(\n    {\n      from: fromAccountId,\n      to: toAccountId,\n      amount: amount,\n      createdAt: new Date()\n    },\n    { session }\n  );\n\n  await session.commitTransaction();\n} catch (error) {\n  await session.abortTransaction();\n  throw error;\n} finally {\n  session.endSession();\n}\n```\n\n## Change Streams\n\n```javascript\n\u002F\u002F Watch for changes in real-time\nconst changeStream = db.orders.watch([\n  { $match: { \"fullDocument.status\": \"pending\" } }\n]);\n\nchangeStream.on(\"change\", (change) => {\n  console.log(\"Change detected:\", change.operationType);\n  console.log(\"Document:\", change.fullDocument);\n\n  if (change.operationType === \"insert\") {\n    \u002F\u002F Process new pending order\n    processNewOrder(change.fullDocument);\n  }\n});\n\n\u002F\u002F Resume from specific point (for fault tolerance)\nconst resumeToken = change._id;\nconst changeStream = db.orders.watch([], {\n  resumeAfter: resumeToken,\n  fullDocument: \"updateLookup\"  \u002F\u002F Include full document on updates\n});\n```\n\n## Spring Data MongoDB Integration\n\n### Entity Class\n\n```java\n@Document(collection = \"users\")\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class User {\n\n    @Id\n    private String id;  \u002F\u002F Maps to _id\n\n    @Indexed(unique = true)\n    private String email;\n\n    private String name;\n\n    @Field(\"password_hash\")  \u002F\u002F Custom field name\n    private String passwordHash;\n\n    @DBRef  \u002F\u002F Reference to another collection\n    private List\u003CRole> roles;\n\n    private Address address;  \u002F\u002F Embedded document\n\n    private List\u003CString> tags;\n\n    @CreatedDate\n    private LocalDateTime createdAt;\n\n    @LastModifiedDate\n    private LocalDateTime updatedAt;\n\n    @Version\n    private Long version;  \u002F\u002F Optimistic locking\n}\n\n@Data\npublic class Address {\n    private String street;\n    private String city;\n    private String zipCode;\n\n    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)\n    private GeoJsonPoint location;\n}\n```\n\n### Repository Interface\n\n```java\npublic interface UserRepository extends MongoRepository\u003CUser, String> {\n\n    \u002F\u002F Derived queries\n    Optional\u003CUser> findByEmail(String email);\n    List\u003CUser> findByNameContainingIgnoreCase(String name);\n    List\u003CUser> findByTagsContaining(String tag);\n\n    \u002F\u002F Custom query with @Query\n    @Query(\"{ 'createdAt': { $gte: ?0 }, 'status': 'active' }\")\n    List\u003CUser> findActiveUsersCreatedAfter(LocalDateTime date);\n\n    \u002F\u002F Projection\n    @Query(value = \"{ 'email': ?0 }\", fields = \"{ 'name': 1, 'email': 1 }\")\n    Optional\u003CUserSummary> findSummaryByEmail(String email);\n\n    \u002F\u002F Aggregation\n    @Aggregation(pipeline = {\n        \"{ $match: { 'status': 'active' } }\",\n        \"{ $group: { _id: '$country', count: { $sum: 1 } } }\",\n        \"{ $sort: { count: -1 } }\"\n    })\n    List\u003CCountryStats> getActiveUsersByCountry();\n\n    \u002F\u002F Geospatial query\n    List\u003CUser> findByAddressLocationNear(Point location, Distance distance);\n}\n```\n\n### MongoTemplate for Complex Queries\n\n```java\n@Service\n@RequiredArgsConstructor\npublic class UserService {\n\n    private final MongoTemplate mongoTemplate;\n\n    public List\u003CUser> searchUsers(UserSearchCriteria criteria) {\n        Query query = new Query();\n\n        if (criteria.getName() != null) {\n            query.addCriteria(Criteria.where(\"name\")\n                .regex(criteria.getName(), \"i\"));\n        }\n\n        if (criteria.getTags() != null && !criteria.getTags().isEmpty()) {\n            query.addCriteria(Criteria.where(\"tags\")\n                .in(criteria.getTags()));\n        }\n\n        if (criteria.getCreatedAfter() != null) {\n            query.addCriteria(Criteria.where(\"createdAt\")\n                .gte(criteria.getCreatedAfter()));\n        }\n\n        query.with(Sort.by(Sort.Direction.DESC, \"createdAt\"));\n        query.with(PageRequest.of(criteria.getPage(), criteria.getSize()));\n\n        return mongoTemplate.find(query, User.class);\n    }\n\n    public AggregationResults\u003CUserStats> getUserStatsByStatus() {\n        Aggregation aggregation = Aggregation.newAggregation(\n            Aggregation.match(Criteria.where(\"createdAt\")\n                .gte(LocalDateTime.now().minusMonths(1))),\n            Aggregation.group(\"status\")\n                .count().as(\"count\")\n                .avg(\"loginCount\").as(\"avgLogins\"),\n            Aggregation.sort(Sort.Direction.DESC, \"count\")\n        );\n\n        return mongoTemplate.aggregate(aggregation, \"users\", UserStats.class);\n    }\n\n    public void bulkUpdateStatus(List\u003CString> userIds, String newStatus) {\n        BulkOperations bulkOps = mongoTemplate.bulkOps(\n            BulkOperations.BulkMode.UNORDERED, User.class);\n\n        for (String userId : userIds) {\n            Query query = Query.query(Criteria.where(\"_id\").is(userId));\n            Update update = Update.update(\"status\", newStatus)\n                .currentDate(\"updatedAt\");\n            bulkOps.updateOne(query, update);\n        }\n\n        bulkOps.execute();\n    }\n}\n```\n\n## Performance Optimization\n\n### Connection Pooling\n\n```java\n\u002F\u002F Spring Boot configuration\nspring:\n  data:\n    mongodb:\n      uri: mongodb:\u002F\u002Flocalhost:27017\u002Fmydb\n      auto-index-creation: false  # Create indexes manually in production\n\n# Connection pool settings (via URI)\n# mongodb:\u002F\u002Flocalhost:27017\u002Fmydb?maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=30000\n```\n\n### Query Optimization\n\n```javascript\n\u002F\u002F Use projections to limit returned fields\ndb.users.find({ status: \"active\" }, { name: 1, email: 1 })\n\n\u002F\u002F Use hint to force specific index\ndb.users.find({ status: \"active\" }).hint({ status: 1, createdAt: -1 })\n\n\u002F\u002F Limit results for pagination\ndb.users.find().sort({ createdAt: -1 }).skip(20).limit(10)\n\n\u002F\u002F Use $exists: false for missing fields (can use index)\ndb.users.createIndex({ optionalField: 1 }, { sparse: true })\ndb.users.find({ optionalField: { $exists: true } })\n```\n\n### Schema Optimization\n\n```javascript\n\u002F\u002F Avoid large arrays (cap at reasonable size)\n\u002F\u002F Use bucketing pattern for time-series data\n{\n  _id: \"sensor1_2024-01-15\",\n  sensorId: \"sensor1\",\n  date: ISODate(\"2024-01-15\"),\n  readings: [\n    { ts: ISODate(\"...\"), value: 23.5 },\n    { ts: ISODate(\"...\"), value: 24.1 },\n    \u002F\u002F ... up to N readings per bucket\n  ],\n  count: 288  \u002F\u002F Track count for full bucket detection\n}\n\n\u002F\u002F Pre-aggregate for reporting\n{\n  _id: \"stats_2024-01\",\n  month: \"2024-01\",\n  totalOrders: 1523,\n  totalRevenue: 152300.50,\n  avgOrderValue: 100.00,\n  topProducts: [\"SKU001\", \"SKU002\", \"SKU003\"]\n}\n```\n\n## Best Practices\n\n### 1. Schema Design\n```javascript\n\u002F\u002F Embed when: data is queried together, bounded arrays\n\u002F\u002F Reference when: unbounded arrays, many-to-many, independent access\n\u002F\u002F Use extended reference pattern for frequently accessed fields\n```\n\n### 2. Indexing\n```javascript\n\u002F\u002F Create indexes for query patterns, not just fields\n\u002F\u002F Use compound indexes following ESR rule\n\u002F\u002F Monitor slow queries: db.setProfilingLevel(1, { slowms: 100 })\n\u002F\u002F Avoid indexing low-cardinality fields alone\n```\n\n### 3. Write Operations\n```javascript\n\u002F\u002F Use bulk operations for multiple writes\n\u002F\u002F Avoid unbounded array growth\n\u002F\u002F Use write concern appropriate to durability needs\ndb.orders.insertOne(doc, { writeConcern: { w: \"majority\" } })\n```\n\n### 4. Read Operations\n```javascript\n\u002F\u002F Always use projections to limit returned data\n\u002F\u002F Use explain() to verify index usage\n\u002F\u002F Prefer aggregation over multiple queries\n\u002F\u002F Use read preference for scaling reads\ndb.orders.find().readPref(\"secondaryPreferred\")\n```\n\n### 5. Connection Management\n```javascript\n\u002F\u002F Use connection pooling\n\u002F\u002F Set appropriate pool size (default: 100)\n\u002F\u002F Handle connection errors with retry logic\n\u002F\u002F Close connections properly on shutdown\n```\n\n## Common Pitfalls\n\n**Unbounded array growth**:\n```javascript\n\u002F\u002F BAD: Comments array grows forever\n{ _id: \"post1\", comments: [...thousands of comments...] }\n\n\u002F\u002F GOOD: Separate collection with references\n{ _id: \"comment1\", postId: \"post1\", text: \"...\" }\n```\n\n**Missing indexes**:\n```javascript\n\u002F\u002F Always create indexes for query patterns\n\u002F\u002F Check with explain() - look for COLLSCAN (bad)\ndb.users.find({ email: \"...\" }).explain()\n```\n\n**Over-indexing**:\n```javascript\n\u002F\u002F Each index adds write overhead\n\u002F\u002F Only index fields used in queries\n\u002F\u002F Monitor index usage: db.users.aggregate([{ $indexStats: {} }])\n```\n\n## Resources\n\n- **MongoDB Documentation**: https:\u002F\u002Fdocs.mongodb.com\u002Fmanual\u002F\n- **MongoDB University**: https:\u002F\u002Funiversity.mongodb.com\u002F\n- **Schema Design Patterns**: https:\u002F\u002Fwww.mongodb.com\u002Fblog\u002Fpost\u002Fbuilding-with-patterns-a-summary\n- **Aggregation Reference**: https:\u002F\u002Fdocs.mongodb.com\u002Fmanual\u002Freference\u002Foperator\u002Faggregation\u002F\n- **Spring Data MongoDB**: https:\u002F\u002Fdocs.spring.io\u002Fspring-data\u002Fmongodb\u002Fdocs\u002Fcurrent\u002Freference\u002Fhtml\u002F\n\n## Related Skills\n\nWhen using MongoDB, consider these complementary skills:\n\n- **spring-boot**: Java framework integration with Spring Data MongoDB\n- **docker**: Running MongoDB in containers\n- **nodejs**: MongoDB with Mongoose ODM\n- **aggregation-pipelines**: Advanced analytics patterns\n","# MongoDB - Document Database Patterns\n\n## Overview\n\nMongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents. It excels at handling unstructured or semi-structured data, hierarchical relationships, and scenarios requiring horizontal scaling.\n\n**Key Features**:\n- Flexible schema (schemaless documents)\n- Rich query language with secondary indexes\n- Aggregation framework for analytics\n- Horizontal scaling (sharding)\n- Replica sets for high availability\n- Change streams for real-time data\n- Geospatial and full-text search\n\n**When to Use MongoDB**:\n- Rapidly evolving schemas\n- Hierarchical\u002Fnested data (embedded documents)\n- Real-time analytics with aggregation\n- Geospatial applications\n- Content management systems\n- IoT data ingestion\n- Catalog\u002Finventory systems\n\n**When NOT to Use MongoDB**:\n- Complex multi-table joins (use RDBMS)\n- ACID transactions across many documents (improved in 4.0+, but limited)\n- Strict schema enforcement requirements\n\n## Schema Design Fundamentals\n\n### Document Structure\n\n```javascript\n\u002F\u002F MongoDB document (BSON format)\n{\n  \"_id\": ObjectId(\"507f1f77bcf86cd799439011\"),  \u002F\u002F Primary key (auto-generated)\n  \"email\": \"alice@example.com\",\n  \"name\": \"Alice Johnson\",\n  \"profile\": {                                   \u002F\u002F Embedded document\n    \"bio\": \"Software developer\",\n    \"avatar\": \"https:\u002F\u002Fexample.com\u002Favatar.jpg\",\n    \"social\": {\n      \"twitter\": \"@alice\",\n      \"github\": \"alice-dev\"\n    }\n  },\n  \"tags\": [\"developer\", \"python\", \"mongodb\"],    \u002F\u002F Array field\n  \"createdAt\": ISODate(\"2024-01-15T10:30:00Z\"),\n  \"updatedAt\": ISODate(\"2024-01-20T14:22:00Z\")\n}\n```\n\n### Embedded vs Referenced Documents\n\n**Embedded (Denormalized)** - Store related data in same document:\n\n```javascript\n\u002F\u002F Embedded: Good for 1:1 or 1:Few relationships\n\u002F\u002F User with embedded address\n{\n  \"_id\": ObjectId(\"...\"),\n  \"name\": \"Alice\",\n  \"address\": {\n    \"street\": \"123 Main St\",\n    \"city\": \"San Francisco\",\n    \"zipCode\": \"94102\"\n  }\n}\n\n\u002F\u002F Embedded: Order with line items (1:Many bounded)\n{\n  \"_id\": ObjectId(\"...\"),\n  \"orderNumber\": \"ORD-2024-001\",\n  \"customer\": { \"name\": \"Alice\", \"email\": \"alice@example.com\" },\n  \"items\": [\n    { \"productId\": \"SKU001\", \"name\": \"Widget\", \"quantity\": 2, \"price\": 29.99 },\n    { \"productId\": \"SKU002\", \"name\": \"Gadget\", \"quantity\": 1, \"price\": 49.99 }\n  ],\n  \"total\": 109.97\n}\n```\n\n**When to Embed**:\n- Data is queried together frequently\n- Child data doesn't make sense without parent\n- 1:1 or 1:Few relationships\n- Child data is bounded (won't grow unbounded)\n- Data doesn't need to be accessed independently\n\n**Referenced (Normalized)** - Store references to other documents:\n\n```javascript\n\u002F\u002F Referenced: Good for 1:Many unbounded or Many:Many\n\u002F\u002F User document\n{\n  \"_id\": ObjectId(\"user123\"),\n  \"name\": \"Alice\",\n  \"email\": \"alice@example.com\"\n}\n\n\u002F\u002F Posts collection (references user)\n{\n  \"_id\": ObjectId(\"post456\"),\n  \"authorId\": ObjectId(\"user123\"),   \u002F\u002F Reference to user\n  \"title\": \"MongoDB Schema Design\",\n  \"content\": \"...\",\n  \"commentCount\": 42\n}\n\n\u002F\u002F Comments collection (references post)\n{\n  \"_id\": ObjectId(\"comment789\"),\n  \"postId\": ObjectId(\"post456\"),     \u002F\u002F Reference to post\n  \"authorId\": ObjectId(\"user999\"),   \u002F\u002F Reference to commenter\n  \"text\": \"Great article!\",\n  \"createdAt\": ISODate(\"2024-01-20T10:00:00Z\")\n}\n```\n\n**When to Reference**:\n- Many:Many relationships\n- 1:Many with unbounded growth (comments, logs)\n- Data is accessed independently\n- Document size would exceed 16MB limit\n- Need atomic updates on referenced document\n\n### Hybrid Pattern (Extended Reference)\n\n```javascript\n\u002F\u002F Post with denormalized author info + reference\n{\n  \"_id\": ObjectId(\"post456\"),\n  \"title\": \"MongoDB Best Practices\",\n  \"content\": \"...\",\n  \"author\": {\n    \"_id\": ObjectId(\"user123\"),      \u002F\u002F Reference for lookups\n    \"name\": \"Alice\",                 \u002F\u002F Denormalized for display\n    \"avatar\": \"https:\u002F\u002F...\"          \u002F\u002F Frequently needed fields\n  },\n  \"commentCount\": 42,\n  \"lastCommentAt\": ISODate(\"...\")\n}\n```\n\n## Query Patterns\n\n### Basic CRUD Operations\n\n```javascript\n\u002F\u002F Find documents\ndb.users.find({ email: \"alice@example.com\" })\ndb.users.find({ age: { $gte: 18, $lte: 65 } })\ndb.users.find({ tags: { $in: [\"developer\", \"designer\"] } })\n\n\u002F\u002F Find with projection (select specific fields)\ndb.users.find(\n  { status: \"active\" },\n  { name: 1, email: 1, _id: 0 }  \u002F\u002F Include name, email; exclude _id\n)\n\n\u002F\u002F Find one\ndb.users.findOne({ email: \"alice@example.com\" })\n\n\u002F\u002F Insert\ndb.users.insertOne({ name: \"Bob\", email: \"bob@example.com\" })\ndb.users.insertMany([\n  { name: \"Charlie\", email: \"charlie@example.com\" },\n  { name: \"Diana\", email: \"diana@example.com\" }\n])\n\n\u002F\u002F Update\ndb.users.updateOne(\n  { email: \"alice@example.com\" },\n  { $set: { name: \"Alice Updated\", updatedAt: new Date() } }\n)\n\ndb.users.updateMany(\n  { status: \"inactive\" },\n  { $set: { archived: true } }\n)\n\n\u002F\u002F Upsert (update or insert)\ndb.users.updateOne(\n  { email: \"new@example.com\" },\n  { $set: { name: \"New User\", createdAt: new Date() } },\n  { upsert: true }\n)\n\n\u002F\u002F Delete\ndb.users.deleteOne({ email: \"bob@example.com\" })\ndb.users.deleteMany({ status: \"deleted\" })\n```\n\n### Query Operators\n\n```javascript\n\u002F\u002F Comparison\ndb.products.find({ price: { $gt: 100 } })        \u002F\u002F Greater than\ndb.products.find({ price: { $gte: 100 } })       \u002F\u002F Greater than or equal\ndb.products.find({ price: { $lt: 50 } })         \u002F\u002F Less than\ndb.products.find({ price: { $lte: 50 } })        \u002F\u002F Less than or equal\ndb.products.find({ price: { $ne: 0 } })          \u002F\u002F Not equal\ndb.products.find({ category: { $in: [\"A\", \"B\"] } })   \u002F\u002F In array\ndb.products.find({ category: { $nin: [\"C\", \"D\"] } })  \u002F\u002F Not in array\n\n\u002F\u002F Logical\ndb.users.find({ $and: [{ age: { $gte: 18 } }, { status: \"active\" }] })\ndb.users.find({ $or: [{ role: \"admin\" }, { role: \"moderator\" }] })\ndb.users.find({ age: { $not: { $lt: 18 } } })\n\n\u002F\u002F Element\ndb.users.find({ middleName: { $exists: true } })  \u002F\u002F Field exists\ndb.users.find({ age: { $type: \"number\" } })       \u002F\u002F Field type\n\n\u002F\u002F Array\ndb.posts.find({ tags: \"mongodb\" })                \u002F\u002F Contains element\ndb.posts.find({ tags: { $all: [\"mongodb\", \"database\"] } })  \u002F\u002F Contains all\ndb.posts.find({ tags: { $size: 3 } })             \u002F\u002F Array size\ndb.posts.find({ \"tags.0\": \"featured\" })           \u002F\u002F First element\n\n\u002F\u002F Embedded documents\ndb.users.find({ \"address.city\": \"San Francisco\" })\ndb.users.find({ \"profile.social.twitter\": { $exists: true } })\n\n\u002F\u002F Regex\ndb.users.find({ name: { $regex: \u002F^alice\u002Fi } })\ndb.users.find({ email: { $regex: \u002F@example\\.com$\u002F } })\n```\n\n### Update Operators\n\n```javascript\n\u002F\u002F Field updates\ndb.users.updateOne(\n  { _id: userId },\n  {\n    $set: { name: \"New Name\" },           \u002F\u002F Set field value\n    $unset: { temporaryField: \"\" },       \u002F\u002F Remove field\n    $rename: { oldName: \"newName\" },      \u002F\u002F Rename field\n    $inc: { loginCount: 1 },              \u002F\u002F Increment\n    $mul: { price: 1.1 },                 \u002F\u002F Multiply\n    $min: { lowestScore: 50 },            \u002F\u002F Set if less than current\n    $max: { highestScore: 100 },          \u002F\u002F Set if greater than current\n    $currentDate: { updatedAt: true }     \u002F\u002F Set to current date\n  }\n)\n\n\u002F\u002F Array updates\ndb.posts.updateOne(\n  { _id: postId },\n  {\n    $push: { tags: \"new-tag\" },           \u002F\u002F Add to array\n    $addToSet: { tags: \"unique-tag\" },    \u002F\u002F Add if not exists\n    $pop: { tags: 1 },                    \u002F\u002F Remove last (-1 for first)\n    $pull: { tags: \"old-tag\" },           \u002F\u002F Remove specific value\n    $pullAll: { tags: [\"a\", \"b\"] }        \u002F\u002F Remove multiple values\n  }\n)\n\n\u002F\u002F Array with modifiers\ndb.posts.updateOne(\n  { _id: postId },\n  {\n    $push: {\n      comments: {\n        $each: [comment1, comment2],      \u002F\u002F Add multiple\n        $sort: { createdAt: -1 },         \u002F\u002F Sort after push\n        $slice: -100                      \u002F\u002F Keep only last 100\n      }\n    }\n  }\n)\n\n\u002F\u002F Positional update (update matched array element)\ndb.posts.updateOne(\n  { _id: postId, \"comments._id\": commentId },\n  { $set: { \"comments.$.text\": \"Updated comment\" } }\n)\n\n\u002F\u002F Update all matching array elements\ndb.posts.updateOne(\n  { _id: postId },\n  { $set: { \"comments.$[elem].read\": true } },\n  { arrayFilters: [{ \"elem.userId\": currentUserId }] }\n)\n```\n\n## Indexing Strategies\n\n### Index Types\n\n```javascript\n\u002F\u002F Single field index\ndb.users.createIndex({ email: 1 })         \u002F\u002F Ascending\ndb.users.createIndex({ createdAt: -1 })    \u002F\u002F Descending\n\n\u002F\u002F Compound index\ndb.orders.createIndex({ customerId: 1, createdAt: -1 })\n\n\u002F\u002F Unique index\ndb.users.createIndex({ email: 1 }, { unique: true })\n\n\u002F\u002F Partial index (index subset of documents)\ndb.orders.createIndex(\n  { createdAt: 1 },\n  { partialFilterExpression: { status: \"pending\" } }\n)\n\n\u002F\u002F TTL index (auto-delete old documents)\ndb.sessions.createIndex(\n  { createdAt: 1 },\n  { expireAfterSeconds: 3600 }  \u002F\u002F Delete after 1 hour\n)\n\n\u002F\u002F Text index (full-text search)\ndb.articles.createIndex({ title: \"text\", content: \"text\" })\n\u002F\u002F Query: db.articles.find({ $text: { $search: \"mongodb tutorial\" } })\n\n\u002F\u002F Geospatial index\ndb.locations.createIndex({ coordinates: \"2dsphere\" })\n\u002F\u002F Query: db.locations.find({\n\u002F\u002F   coordinates: {\n\u002F\u002F     $near: {\n\u002F\u002F       $geometry: { type: \"Point\", coordinates: [-122.4, 37.8] },\n\u002F\u002F       $maxDistance: 5000  \u002F\u002F meters\n\u002F\u002F     }\n\u002F\u002F   }\n\u002F\u002F })\n\n\u002F\u002F Multikey index (for array fields - automatic)\ndb.posts.createIndex({ tags: 1 })\n\n\u002F\u002F Hashed index (for sharding)\ndb.users.createIndex({ email: \"hashed\" })\n```\n\n### Index Best Practices\n\n```javascript\n\u002F\u002F ESR Rule for compound indexes: Equality, Sort, Range\n\u002F\u002F Query: find users where status = \"active\", sorted by createdAt, age > 18\n\u002F\u002F Index: { status: 1, createdAt: -1, age: 1 }\n\u002F\u002F        ^Equality   ^Sort          ^Range\n\n\u002F\u002F Covered queries (all fields in index)\ndb.users.createIndex({ email: 1, name: 1, status: 1 })\ndb.users.find(\n  { email: \"alice@example.com\" },\n  { name: 1, status: 1, _id: 0 }  \u002F\u002F All fields from index\n)\n\u002F\u002F Check with explain: \"totalDocsExamined\": 0\n\n\u002F\u002F Analyze query performance\ndb.users.find({ email: \"alice@example.com\" }).explain(\"executionStats\")\n\u002F\u002F Look for:\n\u002F\u002F - IXSCAN (index scan) vs COLLSCAN (collection scan)\n\u002F\u002F - totalDocsExamined vs totalKeysExamined\n\u002F\u002F - executionTimeMillis\n\n\u002F\u002F List indexes\ndb.users.getIndexes()\n\n\u002F\u002F Drop index\ndb.users.dropIndex(\"email_1\")\ndb.users.dropIndex({ email: 1, name: 1 })\n```\n\n## Aggregation Pipeline\n\n### Pipeline Stages\n\n```javascript\n\u002F\u002F Basic aggregation structure\ndb.orders.aggregate([\n  { $match: { status: \"completed\" } },           \u002F\u002F Filter (like WHERE)\n  { $group: { _id: \"$customerId\", total: { $sum: \"$amount\" } } },  \u002F\u002F Group\n  { $sort: { total: -1 } },                      \u002F\u002F Sort\n  { $limit: 10 }                                 \u002F\u002F Limit results\n])\n\n\u002F\u002F Common stages\ndb.collection.aggregate([\n  \u002F\u002F $match - Filter documents\n  { $match: { status: \"active\", createdAt: { $gte: ISODate(\"2024-01-01\") } } },\n\n  \u002F\u002F $project - Reshape documents (include\u002Fexclude\u002Fcompute fields)\n  { $project: {\n    name: 1,\n    email: 1,\n    fullName: { $concat: [\"$firstName\", \" \", \"$lastName\"] },\n    yearCreated: { $year: \"$createdAt\" }\n  }},\n\n  \u002F\u002F $addFields - Add new fields (keeps existing)\n  { $addFields: {\n    totalPrice: { $multiply: [\"$price\", \"$quantity\"] }\n  }},\n\n  \u002F\u002F $group - Group and aggregate\n  { $group: {\n    _id: \"$category\",\n    count: { $sum: 1 },\n    totalRevenue: { $sum: \"$amount\" },\n    avgPrice: { $avg: \"$price\" },\n    maxPrice: { $max: \"$price\" },\n    products: { $push: \"$name\" },          \u002F\u002F Collect into array\n    uniqueTags: { $addToSet: \"$tag\" }      \u002F\u002F Unique values\n  }},\n\n  \u002F\u002F $sort\n  { $sort: { totalRevenue: -1, count: 1 } },\n\n  \u002F\u002F $skip and $limit (pagination)\n  { $skip: 20 },\n  { $limit: 10 },\n\n  \u002F\u002F $unwind - Deconstruct array field\n  { $unwind: \"$tags\" },\n  \u002F\u002F { tags: [\"a\", \"b\"] } becomes { tags: \"a\" }, { tags: \"b\" }\n\n  \u002F\u002F $lookup - Join collections\n  { $lookup: {\n    from: \"users\",\n    localField: \"authorId\",\n    foreignField: \"_id\",\n    as: \"author\"\n  }},\n  { $unwind: \"$author\" },  \u002F\u002F Convert single-element array to object\n\n  \u002F\u002F $facet - Multiple pipelines in parallel\n  { $facet: {\n    results: [{ $skip: 0 }, { $limit: 10 }],\n    totalCount: [{ $count: \"count\" }]\n  }}\n])\n```\n\n### Real-World Aggregation Examples\n\n```javascript\n\u002F\u002F Sales analytics by month\ndb.orders.aggregate([\n  { $match: { status: \"completed\" } },\n  { $group: {\n    _id: {\n      year: { $year: \"$createdAt\" },\n      month: { $month: \"$createdAt\" }\n    },\n    totalSales: { $sum: \"$amount\" },\n    orderCount: { $sum: 1 },\n    avgOrderValue: { $avg: \"$amount\" }\n  }},\n  { $sort: { \"_id.year\": -1, \"_id.month\": -1 } }\n])\n\n\u002F\u002F Top customers with order details\ndb.orders.aggregate([\n  { $match: { createdAt: { $gte: ISODate(\"2024-01-01\") } } },\n  { $group: {\n    _id: \"$customerId\",\n    totalSpent: { $sum: \"$amount\" },\n    orderCount: { $sum: 1 },\n    lastOrder: { $max: \"$createdAt\" }\n  }},\n  { $sort: { totalSpent: -1 } },\n  { $limit: 10 },\n  { $lookup: {\n    from: \"customers\",\n    localField: \"_id\",\n    foreignField: \"_id\",\n    as: \"customer\"\n  }},\n  { $unwind: \"$customer\" },\n  { $project: {\n    customerName: \"$customer.name\",\n    customerEmail: \"$customer.email\",\n    totalSpent: 1,\n    orderCount: 1,\n    lastOrder: 1\n  }}\n])\n\n\u002F\u002F Product category performance with nested unwind\ndb.orders.aggregate([\n  { $unwind: \"$items\" },\n  { $lookup: {\n    from: \"products\",\n    localField: \"items.productId\",\n    foreignField: \"_id\",\n    as: \"product\"\n  }},\n  { $unwind: \"$product\" },\n  { $group: {\n    _id: \"$product.category\",\n    totalRevenue: { $sum: { $multiply: [\"$items.quantity\", \"$items.price\"] } },\n    unitsSold: { $sum: \"$items.quantity\" },\n    uniqueProducts: { $addToSet: \"$product._id\" }\n  }},\n  { $addFields: {\n    uniqueProductCount: { $size: \"$uniqueProducts\" }\n  }},\n  { $sort: { totalRevenue: -1 } }\n])\n```\n\n## Transactions (MongoDB 4.0+)\n\n```javascript\n\u002F\u002F Multi-document transaction\nconst session = client.startSession();\n\ntry {\n  session.startTransaction();\n\n  \u002F\u002F Transfer money between accounts\n  await accounts.updateOne(\n    { _id: fromAccountId },\n    { $inc: { balance: -amount } },\n    { session }\n  );\n\n  await accounts.updateOne(\n    { _id: toAccountId },\n    { $inc: { balance: amount } },\n    { session }\n  );\n\n  await transactions.insertOne(\n    {\n      from: fromAccountId,\n      to: toAccountId,\n      amount: amount,\n      createdAt: new Date()\n    },\n    { session }\n  );\n\n  await session.commitTransaction();\n} catch (error) {\n  await session.abortTransaction();\n  throw error;\n} finally {\n  session.endSession();\n}\n```\n\n## Change Streams\n\n```javascript\n\u002F\u002F Watch for changes in real-time\nconst changeStream = db.orders.watch([\n  { $match: { \"fullDocument.status\": \"pending\" } }\n]);\n\nchangeStream.on(\"change\", (change) => {\n  console.log(\"Change detected:\", change.operationType);\n  console.log(\"Document:\", change.fullDocument);\n\n  if (change.operationType === \"insert\") {\n    \u002F\u002F Process new pending order\n    processNewOrder(change.fullDocument);\n  }\n});\n\n\u002F\u002F Resume from specific point (for fault tolerance)\nconst resumeToken = change._id;\nconst changeStream = db.orders.watch([], {\n  resumeAfter: resumeToken,\n  fullDocument: \"updateLookup\"  \u002F\u002F Include full document on updates\n});\n```\n\n## Spring Data MongoDB Integration\n\n### Entity Class\n\n```java\n@Document(collection = \"users\")\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class User {\n\n    @Id\n    private String id;  \u002F\u002F Maps to _id\n\n    @Indexed(unique = true)\n    private String email;\n\n    private String name;\n\n    @Field(\"password_hash\")  \u002F\u002F Custom field name\n    private String passwordHash;\n\n    @DBRef  \u002F\u002F Reference to another collection\n    private List\u003CRole> roles;\n\n    private Address address;  \u002F\u002F Embedded document\n\n    private List\u003CString> tags;\n\n    @CreatedDate\n    private LocalDateTime createdAt;\n\n    @LastModifiedDate\n    private LocalDateTime updatedAt;\n\n    @Version\n    private Long version;  \u002F\u002F Optimistic locking\n}\n\n@Data\npublic class Address {\n    private String street;\n    private String city;\n    private String zipCode;\n\n    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)\n    private GeoJsonPoint location;\n}\n```\n\n### Repository Interface\n\n```java\npublic interface UserRepository extends MongoRepository\u003CUser, String> {\n\n    \u002F\u002F Derived queries\n    Optional\u003CUser> findByEmail(String email);\n    List\u003CUser> findByNameContainingIgnoreCase(String name);\n    List\u003CUser> findByTagsContaining(String tag);\n\n    \u002F\u002F Custom query with @Query\n    @Query(\"{ 'createdAt': { $gte: ?0 }, 'status': 'active' }\")\n    List\u003CUser> findActiveUsersCreatedAfter(LocalDateTime date);\n\n    \u002F\u002F Projection\n    @Query(value = \"{ 'email': ?0 }\", fields = \"{ 'name': 1, 'email': 1 }\")\n    Optional\u003CUserSummary> findSummaryByEmail(String email);\n\n    \u002F\u002F Aggregation\n    @Aggregation(pipeline = {\n        \"{ $match: { 'status': 'active' } }\",\n        \"{ $group: { _id: '$country', count: { $sum: 1 } } }\",\n        \"{ $sort: { count: -1 } }\"\n    })\n    List\u003CCountryStats> getActiveUsersByCountry();\n\n    \u002F\u002F Geospatial query\n    List\u003CUser> findByAddressLocationNear(Point location, Distance distance);\n}\n```\n\n### MongoTemplate for Complex Queries\n\n```java\n@Service\n@RequiredArgsConstructor\npublic class UserService {\n\n    private final MongoTemplate mongoTemplate;\n\n    public List\u003CUser> searchUsers(UserSearchCriteria criteria) {\n        Query query = new Query();\n\n        if (criteria.getName() != null) {\n            query.addCriteria(Criteria.where(\"name\")\n                .regex(criteria.getName(), \"i\"));\n        }\n\n        if (criteria.getTags() != null && !criteria.getTags().isEmpty()) {\n            query.addCriteria(Criteria.where(\"tags\")\n                .in(criteria.getTags()));\n        }\n\n        if (criteria.getCreatedAfter() != null) {\n            query.addCriteria(Criteria.where(\"createdAt\")\n                .gte(criteria.getCreatedAfter()));\n        }\n\n        query.with(Sort.by(Sort.Direction.DESC, \"createdAt\"));\n        query.with(PageRequest.of(criteria.getPage(), criteria.getSize()));\n\n        return mongoTemplate.find(query, User.class);\n    }\n\n    public AggregationResults\u003CUserStats> getUserStatsByStatus() {\n        Aggregation aggregation = Aggregation.newAggregation(\n            Aggregation.match(Criteria.where(\"createdAt\")\n                .gte(LocalDateTime.now().minusMonths(1))),\n            Aggregation.group(\"status\")\n                .count().as(\"count\")\n                .avg(\"loginCount\").as(\"avgLogins\"),\n            Aggregation.sort(Sort.Direction.DESC, \"count\")\n        );\n\n        return mongoTemplate.aggregate(aggregation, \"users\", UserStats.class);\n    }\n\n    public void bulkUpdateStatus(List\u003CString> userIds, String newStatus) {\n        BulkOperations bulkOps = mongoTemplate.bulkOps(\n            BulkOperations.BulkMode.UNORDERED, User.class);\n\n        for (String userId : userIds) {\n            Query query = Query.query(Criteria.where(\"_id\").is(userId));\n            Update update = Update.update(\"status\", newStatus)\n                .currentDate(\"updatedAt\");\n            bulkOps.updateOne(query, update);\n        }\n\n        bulkOps.execute();\n    }\n}\n```\n\n## Performance Optimization\n\n### Connection Pooling\n\n```java\n\u002F\u002F Spring Boot configuration\nspring:\n  data:\n    mongodb:\n      uri: mongodb:\u002F\u002Flocalhost:27017\u002Fmydb\n      auto-index-creation: false  # Create indexes manually in production\n\n# Connection pool settings (via URI)\n# mongodb:\u002F\u002Flocalhost:27017\u002Fmydb?maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=30000\n```\n\n### Query Optimization\n\n```javascript\n\u002F\u002F Use projections to limit returned fields\ndb.users.find({ status: \"active\" }, { name: 1, email: 1 })\n\n\u002F\u002F Use hint to force specific index\ndb.users.find({ status: \"active\" }).hint({ status: 1, createdAt: -1 })\n\n\u002F\u002F Limit results for pagination\ndb.users.find().sort({ createdAt: -1 }).skip(20).limit(10)\n\n\u002F\u002F Use $exists: false for missing fields (can use index)\ndb.users.createIndex({ optionalField: 1 }, { sparse: true })\ndb.users.find({ optionalField: { $exists: true } })\n```\n\n### Schema Optimization\n\n```javascript\n\u002F\u002F Avoid large arrays (cap at reasonable size)\n\u002F\u002F Use bucketing pattern for time-series data\n{\n  _id: \"sensor1_2024-01-15\",\n  sensorId: \"sensor1\",\n  date: ISODate(\"2024-01-15\"),\n  readings: [\n    { ts: ISODate(\"...\"), value: 23.5 },\n    { ts: ISODate(\"...\"), value: 24.1 },\n    \u002F\u002F ... up to N readings per bucket\n  ],\n  count: 288  \u002F\u002F Track count for full bucket detection\n}\n\n\u002F\u002F Pre-aggregate for reporting\n{\n  _id: \"stats_2024-01\",\n  month: \"2024-01\",\n  totalOrders: 1523,\n  totalRevenue: 152300.50,\n  avgOrderValue: 100.00,\n  topProducts: [\"SKU001\", \"SKU002\", \"SKU003\"]\n}\n```\n\n## Best Practices\n\n### 1. Schema Design\n```javascript\n\u002F\u002F Embed when: data is queried together, bounded arrays\n\u002F\u002F Reference when: unbounded arrays, many-to-many, independent access\n\u002F\u002F Use extended reference pattern for frequently accessed fields\n```\n\n### 2. Indexing\n```javascript\n\u002F\u002F Create indexes for query patterns, not just fields\n\u002F\u002F Use compound indexes following ESR rule\n\u002F\u002F Monitor slow queries: db.setProfilingLevel(1, { slowms: 100 })\n\u002F\u002F Avoid indexing low-cardinality fields alone\n```\n\n### 3. Write Operations\n```javascript\n\u002F\u002F Use bulk operations for multiple writes\n\u002F\u002F Avoid unbounded array growth\n\u002F\u002F Use write concern appropriate to durability needs\ndb.orders.insertOne(doc, { writeConcern: { w: \"majority\" } })\n```\n\n### 4. Read Operations\n```javascript\n\u002F\u002F Always use projections to limit returned data\n\u002F\u002F Use explain() to verify index usage\n\u002F\u002F Prefer aggregation over multiple queries\n\u002F\u002F Use read preference for scaling reads\ndb.orders.find().readPref(\"secondaryPreferred\")\n```\n\n### 5. Connection Management\n```javascript\n\u002F\u002F Use connection pooling\n\u002F\u002F Set appropriate pool size (default: 100)\n\u002F\u002F Handle connection errors with retry logic\n\u002F\u002F Close connections properly on shutdown\n```\n\n## Common Pitfalls\n\n**Unbounded array growth**:\n```javascript\n\u002F\u002F BAD: Comments array grows forever\n{ _id: \"post1\", comments: [...thousands of comments...] }\n\n\u002F\u002F GOOD: Separate collection with references\n{ _id: \"comment1\", postId: \"post1\", text: \"...\" }\n```\n\n**Missing indexes**:\n```javascript\n\u002F\u002F Always create indexes for query patterns\n\u002F\u002F Check with explain() - look for COLLSCAN (bad)\ndb.users.find({ email: \"...\" }).explain()\n```\n\n**Over-indexing**:\n```javascript\n\u002F\u002F Each index adds write overhead\n\u002F\u002F Only index fields used in queries\n\u002F\u002F Monitor index usage: db.users.aggregate([{ $indexStats: {} }])\n```\n\n## Resources\n\n- **MongoDB Documentation**: https:\u002F\u002Fdocs.mongodb.com\u002Fmanual\u002F\n- **MongoDB University**: https:\u002F\u002Funiversity.mongodb.com\u002F\n- **Schema Design Patterns**: https:\u002F\u002Fwww.mongodb.com\u002Fblog\u002Fpost\u002Fbuilding-with-patterns-a-summary\n- **Aggregation Reference**: https:\u002F\u002Fdocs.mongodb.com\u002Fmanual\u002Freference\u002Foperator\u002Faggregation\u002F\n- **Spring Data MongoDB**: https:\u002F\u002Fdocs.spring.io\u002Fspring-data\u002Fmongodb\u002Fdocs\u002Fcurrent\u002Freference\u002Fhtml\u002F\n\n## Related Skills\n\nWhen using MongoDB, consider these complementary skills:\n\n- **spring-boot**: Java framework integration with Spring Data MongoDB\n- **docker**: Running MongoDB in containers\n- **nodejs**: MongoDB with Mongoose ODM\n- **aggregation-pipelines**: Advanced analytics patterns\n",{"name":5,"tags":24,"author":32,"license":15,"version":33,"category":34,"description":7,"context_limit":35,"requires_tools":36,"progressive_disclosure":37},[5,25,26,27,28,29,30,31],"nosql","database","document-database","aggregation","indexing","spring-data","schema-design","Claude MPM Team","1.0.0","toolchain",700,[],{"entry_point":38},{"summary":39,"quick_start":40,"when_to_use":41},"Document-oriented NoSQL database with flexible schemas, powerful aggregation framework, horizontal scaling, and rich query language","1. Design documents (embedded vs referenced) 2. Create indexes for queries 3. Use aggregation for analytics 4. Implement proper connection pooling","Building apps with flexible\u002Fevolving schemas, hierarchical data, real-time analytics, geospatial queries, or need horizontal scaling","main","590aa4fe05d1ec71a02ee9cc76c9a20508b5bcea","skills\u002Fju\u002Fskills\u002Fmongodb","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha","https:\u002F\u002Fgithub.com\u002Fjulio211916","Estudiante de ing sistemas y psicologia","2026-05-22 04:43:54",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill mongodb",{"tool":55,"command":56},"bunx","bunx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill mongodb",{"tool":58,"command":59},"pnpm","pnpm dlx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill mongodb","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fmongodb\u002FSKILL.md",true,[],[64,71,78,85,92,99],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M735PMP7K29TEC1BC5A3VJ3Z","simpy","Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics, or any system where entities interact with shared resources over time.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fsimpy\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M735NX56AZHYMV3BQ8GYZ7J0","shopify-expert","Builds and debugs Shopify themes (.liquid files, theme.json, sections), develops custom Shopify apps (shopify.app.toml, OAuth, webhooks), and implements Storefront API integrations for headless storefronts. Use when building or customizing Shopify themes, creating Hydrogen or custom React storefronts, developing Shopify apps, implementing checkout UI extensions or Shopify Functions, optimizing performance, or integrating third-party services. Invoke for Liquid templating, Storefront API, app development, checkout customization, Shopify Plus features, App Bridge, Polaris, or Shopify CLI workflows.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshopify-expert\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M735N9WTN69TVA2T5VS9W1CA","shap","Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshap\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M735N3VQ8R56TXFF16BMF19H","shadcn-ui","Deep expertise on shadcn\u002Fui component library including installation, customization, theming, and accessibility patterns. Use when building UI with shadcn\u002Fui components, integrating Radix UI primitives, configuring Tailwind CSS v4 themes, or implementing dark mode. Covers Next.js App Router, Pages Router, and Vite setups.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshadcn-ui\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M735KH64KS6Z58H6BJWX89BV","seoul-subway-arrival","Look up Seoul real-time subway arrival information with the official Seoul Open Data API. Use when the user asks when a train arrives, which trains are approaching a station, or how crowded Seoul subway timing looks right now.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseoul-subway-arrival\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M735K7KAFBZNACQ66PMDQMQD","seo-optimization","Comprehensive 7-phase SEO optimization workflow covering technical SEO auditing, keyword research strategy, on-page optimization, content SEO and E-E-A-T, structured data implementation, link building, and AI search optimization. Use when auditing search engine visibility, diagnosing ranking issues, implementing schema markup, conducting keyword research, optimizing content for E-E-A-T signals, or adapting for AI-driven search (AI Overviews, SGE).","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseo-optimization\u002FSKILL.md",[],[]]