简体   繁体   English

MongoDB - 查找其中数组包含查询数组中的任何项目的文档

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

I have Schema我有架构

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

I have a skill array我有skill

skill = ['python', 'css'] 

I want all the people that match at least one skill from the skill array.我想要所有匹配技能阵列中至少一项技能的人。

$all and $in retrieve only people that match all the skills in the skill array but I want the people that match at least one skill from the skill array. $all$in只检索匹配skill数组中所有技能的人,但我想要匹配skill数组中至少一项技能的人。

You can use $setIntersection .您可以使用$setIntersection

  1. $setIntersection - Intersect the input skill array with skill field and returns a array with common (intersect) value(s). $setIntersection - 将输入技能数组与skill字段相交,并返回一个具有共同(相交)值的数组。
  2. $ne - Filter the document with result from (1) is not empty array. $ne - 使用 (1) 的结果过滤文档不是空数组。
db.collection.find({
  $expr: {
    $ne: [
      {
        $setIntersection: [
          [
            "python",
            "css"
          ],
          "$skill"
        ]
      },
      []
    ]
  }
})

Sample Mongo Playground示例 Mongo Playground

You can use "$in" for your purpose.您可以使用"$in"来达到您的目的。 Perhaps you had some other issue when you tried it before.也许您之前尝试过时遇到了其他问题。

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

Try it on mongoplayground.net .mongoplayground.net上试试。

Just for fun, here's another mongoplayground.net example that uses a mgodatagen configuration to generate the collection.只是为了好玩,这是另一个使用mgodatagen配置生成集合的mongoplayground.net示例。 The query is the same.查询是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM