我有这样的架构
'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"开头。我怎么能用猫鼬做到这一点?
答案 0 :(得分:4)
看看这是否有效......
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/]}}
] })
如果不区分大小写,请检查:How do I make case-insensitive queries on Mongodb?