如何在猫鼬中查询嵌套数组
how to query nested arrays in mongoose
我有这样的模式
'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" 开头的 subject/topic/module/class 的老师。我怎样才能用猫鼬做到这一点?
看看这是否有效...
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?
我有这样的模式
'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" 开头的 subject/topic/module/class 的老师。我怎样才能用猫鼬做到这一点?
看看这是否有效...
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?