如何在Mongoose中查询嵌套数组

12

我有一个像这样的模式

'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var TeacherSchema = new Schema({
    education: [{degree: String, instituteName: String}],
    dob: Date,
    photoUrl: String,
    phoneNumber: String,
    institutes: [{type: mongoose.Schema.ObjectId, ref: 'Institute'}],
    subjects: [{
        name: String,
        topics: [{
            name: String,
            modules: [{
                name: String,
                classes: [{
                    name: String,
                    startTime: Date,
                    endTime: Date,
                    fee: Number
                }]
            }]
        }]
    }],
    created: {type: Date, default: Date.now}
})

module.exports = mongoose.model('Teacher', TeacherSchema);

我的问题是如何在嵌套数组中进行查询?具体来说,假设我想找到所有至少有一个名称以“Math”开头的科目/主题/模块/类的教师。我该如何在mongoose中实现?

1个回答

16

看看这个是否可行...

db.Teacher.find({$or:
[{'subjects':{"$elemMatch":{'name':'Math'}}},
{'subjects.topics':{"$elemMatch":{'name':'Math'}}},
{'subjects.topics.modules.classes':{"$elemMatch":{'name':'Math'}}}]
})

然而,我很好奇为什么需要一个模块数组,当它仅包含一个类数组时?

比方说,如果你想要使用通配符 "ath" 进行搜索。

db.stack30173606.find({$or: [
{'subjects':{"$elemMatch":{'name':'Math'}}}, 
{'subjects.topics':{"$elemMatch":{'name':'math'}}}, 
{'subjects.topics.modules':{"$elemMatch":{'name':'Math'}}}, 
{'subjects.topics.modules.classes.name':{"$in":[/math/]}}
] })

要实现大小写不敏感,可以参考:如何在Mongodb上实现大小写不敏感的查询?


这个代码可以运行,但只有当名称与我给出的相等时才有效。如何实现模糊匹配和不区分大小写? - Raghvendra Singh
我试过了,但它不起作用。这是我的老师主题:"subjects" : [ { "name" : "数学", "topics" : [ { "name" : "数学主题", "modules" : [ { "name" : "数学模块","classes" : [ { "name" : "数学课程" } ] } ] } ] } ]为了适应评论区,我删除了一些内容。这是我的查询:db.teachers.find({$or: [{'subjects':{"$elemMatch":{'name':'Math'}}}, {'subjects.topics':{"$elemMatch":{'name':'math'}}}, {'subjects.topics.modules':{"$elemMatch":{'name':'Math'}}}, {'subjects.topics.modules.classes':{"$in":[/math/]}}] });但它没有返回任何结果。 - Raghvendra Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接