【问题标题】:how to query nested arrays in mongoose如何在猫鼬中查询嵌套数组
【发布时间】:2015-05-13 05:50:05
【问题描述】:

我有这样的架构

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

我的问题是如何在嵌套数组中查询?具体来说,假设我想找到所有至少有一个主题/主题/模块/课程名称以“数学”开头的老师。我怎么能用猫鼬做到这一点?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    看看这是否有效...

    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?

    【讨论】:

    • 谢谢。这有效,但前提是名称等于我给出的名称。我怎样才能做到这一点,不区分大小写??
    • 我试过它不起作用这是我在老师“主题”中的主题:[{“名称”:“数学”,“主题”:[{“名称”:“数学主题” , "modules" : [ { "name" : "math module","classes" : [ { "name" : "math class" } ] } ] } ] } ] 我删除了一些内容以适应评论。这是我的查询 db.teachers.find({$or: [{'subjects':{"$elemMatch":{'name':'Math'}}}, {'subjects.topics':{"$elemMatch" :{'name':'math'}}}, {'subjects.topics.modules':{"$elemMatch":{'name':'Math'}}}, {'subjects.topics.modules.classes' :{"$in":[/math/]}}] });它什么也没给我。
    猜你喜欢
    • 2021-03-23
    • 2021-08-08
    • 2020-05-23
    • 2021-05-06
    • 2019-04-05
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多