查找数组与查询数组中的任何项目匹配的文档 | mongodb
Find document in which array match any items in query array | mongodb
我有架构
person = {
skill = [{
type: String
}]
name = { type : String}
}
我有技能阵
skill = ['python', 'css']
我想要所有匹配技能数组中至少一项技能的人。
$all 和 $in 只检索匹配技能数组中所有技能的人,但我想要至少匹配技能数组中技能的技能人。
您可以使用 $setIntersection
。
$setIntersection
- 将输入技能数组与 skill
字段和 returns 具有公共(相交)值的数组相交。
$ne
- 过滤结果来自 (1) 的文档不是空数组。
db.collection.find({
$expr: {
$ne: [
{
$setIntersection: [
[
"python",
"css"
],
"$skill"
]
},
[]
]
}
})
您可以根据自己的目的使用 "$in"
。可能你之前试过的时候遇到了其他问题。
db.collection.find({
"skill": {
"$in": [ "python", "css" ]
}
})
在 mongoplayground.net 上试用。
只是为了好玩,这里有另一个 mongoplayground.net example that uses a mgodatagen 配置来生成集合。查询相同。
我有架构
person = {
skill = [{
type: String
}]
name = { type : String}
}
我有技能阵
skill = ['python', 'css']
我想要所有匹配技能数组中至少一项技能的人。
$all 和 $in 只检索匹配技能数组中所有技能的人,但我想要至少匹配技能数组中技能的技能人。
您可以使用 $setIntersection
。
$setIntersection
- 将输入技能数组与skill
字段和 returns 具有公共(相交)值的数组相交。$ne
- 过滤结果来自 (1) 的文档不是空数组。
db.collection.find({
$expr: {
$ne: [
{
$setIntersection: [
[
"python",
"css"
],
"$skill"
]
},
[]
]
}
})
您可以根据自己的目的使用 "$in"
。可能你之前试过的时候遇到了其他问题。
db.collection.find({
"skill": {
"$in": [ "python", "css" ]
}
})
在 mongoplayground.net 上试用。
只是为了好玩,这里有另一个 mongoplayground.net example that uses a mgodatagen 配置来生成集合。查询相同。