MongoDB返回匹配查询数组中一个元素的集合

时间:2020-04-12 09:26:41

标签: mongodb mongoose mongodb-query

这是数据库集合-作业:

{
  "skillsRequired": ["html", "css", "javascript"],
  "qualification": [ "BE", "B-Tech"],
  "company" : "microsoft"
},
{
  "skillsRequired": ["html", "ml", "ai", "python"],
  "qualification": [ "BE", "B-Tech"],
  "company" : "microsoft"
},
{
  "skillsRequired": ["ml", "ai", "python"],
  "qualification": [ "BE", "B-Tech"],
  "company" : "microsoft"
}

当参数为“ skillsRequired”时,如何获取以下输出:[“ html”,“ css”]

[{
  "skillsRequired": ["html", "css", "javascript"],
  "qualification": [ "BE", "B-Tech"],
  "company" : "microsoft"
},
{
  "skillsRequired": ["html", "ml", "ai", "python"],
  "qualification": [ "BE", "B-Tech"],
  "company" : "microsoft"
}]

简而言之,查询应该返回所有记录/文档,其中参数查询中的任何一个元素都与文档中的任何元素匹配。

1 个答案:

答案 0 :(得分:1)

const query = {};

if (skillsRequiredParam && skillsRequiredParam.length > 0) 
    query.skillsRequired = {$in: skillsRequiredParam}
}     
const docs = await db.collection.find(query).exec();