gpt4 book ai didi

node.js - 如何在 Mongoose 中查询嵌套数组

转载 作者:可可西里 更新时间:2023-11-01 09:12:21 24 4
gpt4 key购买 nike

我有这样的模式

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

我的问题是如何查询嵌套数组?具体来说,我想找到所有至少有一个主题/主题/模块/类(class)名称以“数学”开头的老师。我怎样才能用 Mongoose 做到这一点?

最佳答案

看看这是否有效...

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?

关于node.js - 如何在 Mongoose 中查询嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30173606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com