我需要有关嵌套对象数组的查询优化的帮助。
我们有大量文档的集合,每个文档都包含嵌套的对象数组,最高可达 3 级,如下所示:
集合名称:产品
收集的文件总数:2000万
每个文档的大小:> = 500 kb
[
{
"_id":"ObjectId('121212')",
"id":999,
"name":"prod1",
"sellers":[
{
"seller_id":99,
"name":"Business 1",
"providers":[
{
"seller_id":99,
"provider_id":1,
"provider_name":"prov 1",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":99,
"provider_id":2,
"provider_name":"prov 2",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
},
{
"seller_id":9,
"name":"Business 2",
"providers":[
{
"seller_id":9,
"provider_id":3,
"provider_name":"prov 3",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":9,
"provider_id":4,
"provider_name":"prov 4",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
}
]
},
{
"_id":"ObjectId('232323')",
"id":1000,
"name":"prod 2",
"sellers":[
{
"seller_id":44,
"product_id":2,
"name":"Business 22",
"providers":[
{
"seller_id":44,
"provider_id":3,
"provider_name":"prov 3",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":44,
"provider_id":4,
"provider_name":"prov 4",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
},
{
"seller_id":91,
"name":"Business 21",
"providers":[
{
"seller_id":91,
"provider_id":1,
"provider_name":"prov 1",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":91,
"provider_id":2,
"provider_name":"prov 2",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
}
]
},
{
"_id":"ObjectId('989798')",
"id":1001,
"name":"prod 3",
"sellers":[
{
"seller_id":33,
"name":"Business 112",
"providers":[
{
"seller_id":33,
"provider_id":1,
"provider_name":"prov 1",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":33,
"provider_id":2,
"provider_name":"prov 2",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
},
{
"seller_id":32,
"name":"Business 2",
"providers":[
{
"seller_id":32,
"provider_id":1,
"provider_name":"prov 1",
"quantity":50,
"order_allowed":40,
"notification_on_stock":true
},
{
"seller_id":32,
"provider_id":2,
"provider_name":"prov 2",
"quantity":20,
"order_allowed":20,
"notification_on_stock":true
}
]
}
]
}
]
我为我的产品系列添加了以下索引,如下所示,
products.id 上的索引
{“身份证”:1}
嵌套数组文档的索引
{ "products.sellers.seller_id":1 }
{
"id":1,
"sellers.seller_id":1,
"sellers.providers.provider_id":1
}
我的查询:
db.products.find({
"id":999,
"sellers":{
"$elemMatch":{
"providers":{
"$elemMatch":{
"seller_id":30098,
"provider_id":517
}
}
}
}
});
我的问题是查询总是在字段 id 上获取第一个索引,并且查询花费了大约 800 毫秒的时间,我需要对其进行优化。