说我的数据库中有以下内容:
knights
{
name: 'Knightley',
skills: [
{ name: 'sword', level: 2 },
{ name: 'shield', level: 1 }
]
},
{
name: 'Cowardly',
skills: [
{ name: 'sword', level: 1 },
{ name: 'shield', level: 5 }
]
}
我想用剑和盾的技能让所有骑士返回。 像这样的东西(伪):
Knight.find({ skills.name: which contains ['sword', 'shield'] })
我如何进行这种查询? 谢谢!
答案 0 :(得分:1)
您需要使用$elemMatch
和$in
运算符在数组内部查找
db.collection.find({
skills: {
$elemMatch: {
name: { $in: ["sword", "shield"] }
}
}
})
输出
[
{
"name": "Knightley",
"skills": [
{
"level": 2,
"name": "sword"
},
{
"level": 1,
"name": "shield"
}
]
},
{
"name": "Cowardly",
"skills": [
{
"level": 1,
"name": "sword"
},
{
"level": 5,
"name": "shield"
}
]
}
]
检查here