我们应该在mongodb中创建哪些索引来提高性能?

时间:2016-05-18 07:42:52

标签: mongodb mongodb-query

我有一个product_catalog集合,它包含大量文档。

文件就像(文件结构):

{
  "_id": "573c1540c4cebf791315aa0a",
  "images": [],
  "categories": [
    "shirts",
    "wedding",
    "suits"
  ],
  "publish": "1",
  "inventory_management": "none",
  "options": [],
  "SEO": {
    "title": "dummy",
    "description": "dfasdfasd",
    "keywords": "dummy"
  },
  "attributes": [],
  "features": [],
  "files": [],
  "seller": "seller_one",
  "approve": "approved",
  "description": "<span style=\"color: rgb(57, 57, 57); font-family: 'Open Sans'; font-size: 14px; line-height: 21px; text-align: right;\">Description here.</span>",
  "name": "dummy",
  "alias": "dummy",
  "price": 500,
  "compare_price": 550,
  "collections": [
    "collection-2",
    "collection-3"
  ],
  "brand": "test_brand",
  "sku": "rtrtrt",
  "barcode": "12121",
  "weight": "12",
  "sort_order": 0,
  "available": 1,
  "uniquesku": [
    "rtrtrt"
  ]
}

我们正在使用以下查询和排序选项检索文档。

db.collection('product_catalog').find(query).sort(sort_options).toArray(function(err, records){

// records

}) 
sort_options : { sort_order: 1, _id: -1 }   
Query is like : 
    1. { publish: '1'}
     2. { publish: '1', alias: 'alias_value' }
     3. { publish: '1', approve: 'approve_value' }
     4. { categories: 'category_value', publish: '1' }
     5. { collections: 'collection_value', publish: '1' }

我们应该创建哪些索引来提高读取操作的性能?

1 个答案:

答案 0 :(得分:1)

在MongoDB中,它建议索引遵循您的应用程序的用例。由于您已经确定了最常见的查询,因此您只需为每个查询添加一个索引:

 { alias:1, publish: 1}
 { approve:1, publish:1}
 { categories: 1, publish: 1 }
 { collections: 1, publish: 1 }
 { publish: 1 }

请注意,我已将发布作为第二个字段,因为第一个字段将更精细,效率更高。