Home > Blockchain >  Find document in which array match any items in query array | mongodb
Find document in which array match any items in query array | mongodb

Time:02-26

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 skill array but I want skill people that match at least skill from skill array.

CodePudding user response:

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

CodePudding user response:

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.

  • Related