面试题答案
一键面试- 设计思路:
- 利用MongoDB的索引来提高查询性能。因为数据量非常大,合适的索引能显著加快查询速度。
- 对于此查询,我们需要在订单详情数组中的商品名称和数量字段上创建复合索引,这样能加快对购买特定商品且数量满足条件的文档的查找。
- 查询优化方案:
- 创建复合索引:在
orders
集合上,对orderDetails.productName
和orderDetails.quantity
字段创建复合索引。 - 利用
$unwind
操作符展开订单详情数组,这样后续可以直接对展开后的文档进行条件匹配。 - 使用
$match
阶段来过滤出满足购买‘商品A’且购买数量超过10件的文档。 - 最后使用
$group
操作符来聚合出所有满足条件的客户。
- 创建复合索引:在
- 具体查询语句:
db.orders.aggregate([
{
$unwind: "$orderDetails"
},
{
$match: {
"orderDetails.productName": "商品A",
"orderDetails.quantity": { $gt: 10 }
}
},
{
$group: {
_id: null,
customers: {
$push: {
name: "$customer.name",
contact: "$customer.contact"
}
}
}
}
]);
上述查询语句通过$unwind
展开订单详情数组,$match
过滤条件,$group
聚合出满足条件的客户信息。同时为了优化查询性能,建议提前在orders
集合上创建如下复合索引:
db.orders.createIndex({ "orderDetails.productName": 1, "orderDetails.quantity": 1 });