How to query nested arrays in mongoose
I have a diagram 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 nested arrays? To be specific, let's say that I want to find all teachers who have at least one subject / topic / module / class whose name starts with "Math". How can I do this with a mongoose?
+3
source to share
1 answer
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 an array of modules is needed when everything it contains is an array of classes?
Let's say you want to search with the 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 insensitivity, check this: How to make case insensitive queries on Mongodb?
+3
source to share