簡體   English   中英

MongoDB - 查找其中數組包含查詢數組中的任何項目的文檔

[英]MongoDB - Find document in which array contains any items in query array

我有架構

person = {
 skill = [{
        type: String
    }]
 name = { type : String}
}

我有skill

skill = ['python', 'css'] 

我想要所有匹配技能陣列中至少一項技能的人。

$all$in只檢索匹配skill數組中所有技能的人,但我想要匹配skill數組中至少一項技能的人。

您可以使用$setIntersection

  1. $setIntersection - 將輸入技能數組與skill字段相交,並返回一個具有共同(相交)值的數組。
  2. $ne - 使用 (1) 的結果過濾文檔不是空數組。
db.collection.find({
  $expr: {
    $ne: [
      {
        $setIntersection: [
          [
            "python",
            "css"
          ],
          "$skill"
        ]
      },
      []
    ]
  }
})

示例 Mongo Playground

您可以使用"$in"來達到您的目的。 也許您之前嘗試過時遇到了其他問題。

db.collection.find({
  "skill": {
    "$in": [ "python", "css" ]
  }
})

mongoplayground.net上試試。

只是為了好玩,這是另一個使用mgodatagen配置生成集合的mongoplayground.net示例。 查詢是一樣的。

暫無
暫無

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

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