查询对象数组以检查其是否包含猫鼬字符串数组

时间:2018-06-21 12:37:14

标签: javascript node.js mongodb mongoose mongoose-schema

说我的数据库中有以下内容:

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'] })

我如何进行这种查询? 谢谢!

1 个答案:

答案 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