文档菜单
文档首页
/
MongoDB 手册
/ /

减少$lookup操作

本页内容

  • 关于此任务
  • 示例
  • 了解更多

关于$lookup操作将多个集合的信息连接到单个文档中。虽然当不经常使用时$lookup操作很有用,但与仅查询单个集合的操作相比,它可能较慢且资源密集。如果您经常使用$lookup操作,请考虑重新设计模式以将相关数据存储在单个集合中。这可以提高查询性能并降低操作成本。

考虑以下具有两个独立集合的模式:productsorders。每个订单可以包含多个产品,您想跟踪每个订单内的产品详细信息以便快速访问。这两个独立的集合通过$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."
}
] )

这种方法可以让您保持集合分离,同时通过将产品集合中的关键字段嵌入到订单集合中来避免多次查询。这提高了读取性能并简化了数据检索,因为您可以在单个查询中访问所有必要信息。然而,考虑潜在的文档大小限制和数据重复是很重要的。

返回

膨胀文档