减少$lookup操作
关于$lookup
操作将多个集合的信息连接到单个文档中。虽然当不经常使用时$lookup
操作很有用,但与仅查询单个集合的操作相比,它可能较慢且资源密集。如果您经常使用$lookup
操作,请考虑重新设计模式以将相关数据存储在单个集合中。这可以提高查询性能并降低操作成本。
关于此任务
考虑以下具有两个独立集合的模式:products
和orders
。每个订单可以包含多个产品,您想跟踪每个订单内的产品详细信息以便快速访问。这两个独立的集合通过$lookup
操作连接。
//products collection db.products.insertMany( [ { _id: 1, name: "Laptop", price: 1000, manufacturer: "TechCorp", category: "Electronics", description: "Fastest computer on the market." }, { _id: 2, name: "Headphones", price: 100, manufacturer: "Sound", category: "Accessories", description: "The latest sound technology." }, { _id: 3, name: "Tablet", price: 200, manufacturer: "TechCorp", category: "Electronics", description: "The most compact tablet." } ] )
//orders collection db.orders.insertMany( [ { _id: 101, customer_name: "John Doe", timestamp: "2024-05-11T010:00:00Z", product_ids: [1, 2], total: 1200 }, { _id: 102, customer_name: "Jane Smith", timestamp: "2024-05-11T012:00:00Z", product_ids: [2], total: 100 } ] )
在此模式中,每次访问订单信息时都需要使用$lookup
操作。执行$lookup
操作会增加查询复杂性并降低性能。为了减少对$lookup
操作的使用,将一起访问的数据存储在单个集合中。
示例
您可以使用子集模式设计模式将产品详情的子集嵌入到订单
集合中。这样可以查询单个集合以返回所需的结果。与订单
集合不相关的产品详情和文档保留在产品
集合中。
//orders collection db.orders.insertMany( [ { _id: 101, customer_name: "John Doe", timestamp: "2024-05-11T10:00:00Z", products: [ { product_id: 1, name: "Laptop", price: 1000 }, { product_id: 2, name: "Headphones", price: 100 } ], total: 1100 }, { _id: 102, customer_name: "Jane Smith", timestamp: "2024-05-11T12:00:00Z", products: [ { product_id: 2, name: "Headphones", price: 100 } ], total: 100 } ] )
//products collection db.products.insertMany( [ { _id: 1, name: "Laptop", price: 1000, manufacturer: "TechCorp", category: "Electronics", description: "Fastest computer on the market." }, { _id: 2, name: "Headphones", price: 100, manufacturer: "Sound", category: "Accessories", description: "The latest sound technology." }, { _id: 3, name: "Tablet", price: 200, manufacturer: "TechCorp", category: "Electronics", description: "The most compact tablet." } ] )
这种方法可以让您保持集合分离,同时通过将产品
集合中的关键字段嵌入到订单
集合中来避免多次查询。这提高了读取性能并简化了数据检索,因为您可以在单个查询中访问所有必要信息。然而,考虑潜在的文档大小限制和数据重复是很重要的。