我需要為以下查詢創建索引:
await Activity.find({
$and: [
{
lastUpdated: {
$gte: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
},
},
{
"followers._user": _user,
},
{
global: true,
}
]
})
.collation({
locale: "en_US",
numericOrdering: true,
})
.sort({
lastUpdated: -1
})
.skip(
length
)
.limit(
10
)
我目前有以下索引,但查詢不使用它。
ActivitiesSchema.index(
{ "followers._user": 1, global: 1, lastUpdated: -1 },
{
collation: {
locale: "en_US",
numericOrdering: true,
},
}
);
如果我遺漏任何資訊或需要提供更多詳細資訊,請告訴我,我很樂意提供。
uj5u.com熱心網友回復:
將索引更改為:
{ lastUpdated: -1, "followers._user": 1, global: 1 }
注意:它可能會影響依賴現有索引的其他查詢
https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-index-prefix讀取:
如果排序鍵對應索引鍵或索引前綴,MongoDB 就可以使用索引對查詢結果進行排序。復合索引的前綴是一個子集,它由索引鍵模式開頭的一個或多個鍵組成。
由于您按“lastUpdated”排序,因此索引應從它開始。
NB 2:有了這個改變 Mongodb可以使用,但不能保證。還有許多其他因素,如選擇性和基數,例如global: true,暗示極低的基數可以從該欄位的索引中受益。另一方面,如果用戶關注的不多且總活動量很大,則按“followers._user”索引過濾并進行記憶體排序可能會更便宜。由查詢規劃器決定使用哪個索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378961.html
