【问题标题】:Create mongodb index based on gt and lt基于gt和lt创建mongodb索引
【发布时间】:2021-08-24 05:43:48
【问题描述】:

我的收藏有许多称为“产品”的文档,
我想通过为其创建索引来提高性能。

问题在于 IDK 索引是如何工作的,所以 IDK 索引是否有用。

我最常用的查询是关于“storeId”和“salesDates”字段
storeId 只是字符串,所以我认为创建索引很好,
但棘手的是salesDates,salesDates 是Object 有两个字段from 和to like this

product { 
 ...someFields,
 storeId: string,
 salesDate  {
  from: Date time Number
  to: Date time Number
 }
}

例如,我的查询基于$gt $lt

product.find({
storeId: "blah",
salesDate.from : {$gt: 1423151234, $lt: 15123123123 }
})

product.find({
storeId: "blah",
salesDate.from: {$gt: 1423151234},
salesDate.to: {$lt: 15123123123 }
})

这个案例的正确索引是多少?

【问题讨论】:

    标签: database mongodb mongoose indexing database-performance


    【解决方案1】:

    对于您的特定用例,我建议您仅在 from 键并在您的查找查询中使用 $ge$le

    原因是您要索引的键数越少(在可以避免多个键查询的情况下)越好。

    确保您按照以下顺序进行索引和查找操作。

    索引命令和命令:

    db,product.createIndex({
         "storeId": 1,
         "salesDate.from": -1,   // Change `-1` to `1` if you want to ISODate key to be indexed in Ascending order
    })
    

    查找命令:

    db,product.find({
         "storeId": "blah",
         "salesDate.from": {$gt: 1423151234, $lt: 15123123123 },
    })
    

    【讨论】:

    • 是的来自更重要,:) 谢谢
    猜你喜欢
    • 2011-05-11
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多