簡體   English   中英

MongoDB 深度數組掃描:多鍵復合索引

[英]MongoDB deep array scan: multikey compound indexing

我有一組客戶及其訪問過的地方,組織如下:

{
  "customer_id": 151,
  "first_name": "Nakia",
  "last_name": "Boyle",
  "visited_places": [
    {
      "country": "Portugal",
      "cities": [
        "South Nicklausburgh",
        "East Graham"
      ]
    },
    {
      "country": "Rwanda",
      "cities": [
        "West Kristofer",
        "Effertzbury",
        "Stokeston",
        "South Darionfort",
        "Lewisport"
      ]
    }
  ]
}

我正在嘗試查找訪問過特定國家/地區特定城市的所有客戶。 查詢對象為:

{
  "visited_places.country" : "Portugal", 
  "visited_places.cities" : "South Nicklausburgh" 
}

這個查詢的理想索引是什么? 我試圖像這樣創建一個復合索引:

collection.createIndex({
  'visited_places.cities': 1,
  'visited_places.country': 1
}

確實使用了該索引,但僅用於查找城市,正如執行計划在 IXSCAN 階段所解釋的那樣:

"indexBounds": {
  "visited_places.cities": [
   "[\"South Nicklausburgh\", \"South Nicklausburgh\"]"
  ],
  "visited_places.country": [
   "[MinKey, MaxKey]"
  ]

該國家在隨后的 FETCH 階段被過濾掉:

"filter": {
  "visited_places.country": {
   "$eq": "Portugal"
  }
 }

為什么不能僅從復合索引完成查詢,對於此模式和查詢,理想的索引是什么?

像這樣使用 $elemMatch

db.collection.find({
  "visited_places": {
    "$elemMatch": {
      "country": "Portugal",
      "cities": {
        "$elemMatch": {
          "$eq": "South Nicklausburgh"
        }
      }
    }
  }
},
)

https://mongoplayground.net/p/CKnz8VCT5rX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM