简体   繁体   中英

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 = ['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.

You can use $setIntersection .

  1. $setIntersection - Intersect the input skill array with skill field and returns a array with common (intersect) value(s).
  2. $ne - Filter the document with result from (1) is not empty array.
db.collection.find({
  $expr: {
    $ne: [
      {
        $setIntersection: [
          [
            "python",
            "css"
          ],
          "$skill"
        ]
      },
      []
    ]
  }
})

Sample Mongo Playground

You can use "$in" for your purpose. Perhaps you had some other issue when you tried it before.

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

Try it on mongoplayground.net .

Just for fun, here's another mongoplayground.net example that uses a mgodatagen configuration to generate the collection. The query is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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