如何在mongoose中查询嵌套数组

时间:2021-01-12 02:33:49

I have a schema like this

我有这样的架构

'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);

My question is how can i query in the nested arrays? To be specific Lets say i want to find all the teachers who have at least one subject/topic/module/class whose name starts with "Math". How can i do that with mongoose?

我的问题是如何在嵌套数组中查询?具体来说可以说我想找到所有至少有一个名称以“Math”开头的主题/主题/模块/类的教师。我怎么能用猫鼬做到这一点?

1 个解决方案

#1


See if this works...

看看这是否有效......

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

However, I am curious to know why a modules array is needed when all it contains is a classes array?

但是,我很想知道为什么当一个模块数组包含一个类数组时需要它?

Let's say you want to search with wildcard "ath"

假设您要使用通配符“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/]}}
] })

For case insensitive, check this: How do I make case-insensitive queries on Mongodb?

对于不区分大小写的情况,请检查以下内容:如何在Mongodb上进行不区分大小写的查询?

#1


See if this works...

看看这是否有效......

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

However, I am curious to know why a modules array is needed when all it contains is a classes array?

但是,我很想知道为什么当一个模块数组包含一个类数组时需要它?

Let's say you want to search with wildcard "ath"

假设您要使用通配符“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/]}}
] })

For case insensitive, check this: How do I make case-insensitive queries on Mongodb?

对于不区分大小写的情况,请检查以下内容:如何在Mongodb上进行不区分大小写的查询?