基于 gt 和 lt 创建 mongodb 索引
Create mongodb index based on gt and lt
我有 Collection 有很多名为“products”的文档,
我想通过为其创建索引来提高性能。
问题在于 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 }
})
这个案例的正确索引是什么?
对于您的具体用例,我建议您仅在
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 },
})
我有 Collection 有很多名为“products”的文档,
我想通过为其创建索引来提高性能。
问题在于 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 }
})
这个案例的正确索引是什么?
对于您的具体用例,我建议您仅在
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 },
})