【问题标题】:Querying array of nested documents for more than one value查询嵌套文档数组的多个值
【发布时间】:2021-07-27 12:58:24
【问题描述】:

我有一个mongodb集合Student如图:

[{
    "name" : "John",
    "age" : 19,
    "hobbies" : [
        {
            "hobbyName" : "Sleeping",
            "proficiency": "Expert"
        }, 
        {
            "hobbyName" : "Coding",
            "proficiency": "Beginner"
        },
        {
            "hobbyName": "Googling",
            "proficiency": "Expert"
        }
    ]
},
{
    "name" : "Michael",
    "age" : 22,
    "hobbies" : [
        {
            "hobbyName" : "Eating",
            "proficiency": "Expert"
        }
    ]
}]

一个学生可以有很多爱好。对于单一爱好的查询,我可以简单地使用Student.find({hobbies.hobbyName: "Coding"})。但是,如果我想找到所有有一个或多个爱好的学生怎么办。假设我想找到所有以编程和睡眠为爱好的学生。查询应该返回所有有这两种爱好的学生。他们可能有也可能没有任何其他爱好。感谢您的帮助!

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    您可以使用$all

    db.Student.find({
      "hobbies.hobbyName": {
        "$all": [
          "Coding",
          "Sleeping"
        ]
      }
    })
    

    Mongo playground

    【讨论】:

    • 我认为 $all 仅适用于查找数组中的项目。它也适用于对象。谢谢!
    猜你喜欢
    • 2020-11-28
    • 2017-09-13
    • 2019-10-09
    • 2021-07-21
    • 1970-01-01
    • 2019-02-20
    • 2015-02-05
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多