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?
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"
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With