【问题标题】:MongoDB Indexing many categories in each product, data modelingMongoDB 索引每个产品中的许多类别,数据建模
【发布时间】:2013-09-29 05:22:04
【问题描述】:

从 MySQL 数据库迁移到 MongoDB,我必须在产品目录中复制此功能:

  1. 每个产品都有多个类别
  2. 每个类别都有产品在每个类别中的名称、ID 和位置
  3. 按类别查询产品、按类别位置或价格和标签等其他字段排序时的性能

这是我提出的模型示例

{
   ...
   categories: [
       {
           name: 'Clothing',
           category_id: 1,
           position: 0
       },
       {
           name: 'Bottoms',
           category_id: 2,
           position: 2
       },
       {
           name: 'Jeans',
           category_id: 5,
           position: 0
       }
   ]
}

我应该将名称、category_id 和位置分隔到不同的顶级字段中以进行索引吗?

【问题讨论】:

  • 无法获取位置字段的含义?
  • @hevi 位置字段用于对类别内的产品进行排序。例如。在底部类别中,我们使用值 2 按位置 DESC 对其进行排序。

标签: mongodb database-design relational-database


【解决方案1】:

根据您提供的文档示例,似乎不可能通过该类别位置的有效索引来按类别执行搜索

当然,您可以索引“位置”、“名称”并运行查询

db.coll.find({"categories.name": "Jeans"}).sort({"categories.position": -1})

但这不会是按所需类别正确排序。

我建议有文档部分:

{
  ...
  "categories": ["Clothing", "Bottoms", "Jeans"],
  "positions": {
    "Clothing": 0,
    "Bottoms": 2,
    "Jeans": 0
  }
}

然后你就可以运行查询了

db.coll.find({categories: "Jeans"}).sort({"positions.Jeans": -1})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多