首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$regex在MongoDB中不起作用

$regex在MongoDB中不起作用
EN

Stack Overflow用户
提问于 2017-11-07 16:34:17
回答 2查看 4.6K关注 0票数 3

我知道有很多与$regex相关的答案,但我已经尝试了几个小时了,我无法让它起作用。

我想要的是找到那些courses,在courseName中包含一个字母"D“。我做错了什么?请帮帮我!

我有以下文件:

代码语言:javascript
复制
{
            "firstName": "Sarah",
            "lastName": "Jepsen",
            "age": 27,
            "courses": [
                {
                    "courseName": "Web-Development",
                    "teachers": [
                        {
                            "firstName": "Santiago",
                            "lastName": "Donoso"
                        }
                    ]
                },

                {
                    "courseName": "Databases",
                    "teachers": [
                        {
                            "firstName": "Dany",
                            "lastName": "Kallas"
                        },
                        {
                            "firstName": "Rune",
                            "lastName": "Lyng"
                        }
                    ]
                },
                {
                    "courseName": "Interface-Design",
                    "teachers": [
                        {
                            "firstName": "Roxana",
                            "lastName": "Stolniceanu"
                        }
                    ]
                }
            ]
        }

这是我的查找查询:

代码语言:javascript
复制
student.findCourses = (fcallback) => {
    global.db.collection('students').find({ "courses.courseName": { $regex: "/D/" }, _id: false }).toArray((err, result) => {

        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        console.log(jOk)
        console.log(JSON.stringify(result))
        return fcallback(false, jOk)
    })
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-07 18:47:55

要获得与正则表达式匹配的所有课程,您必须手动筛选它们。考虑您的情况,使用另一个courses数组项:

代码语言:javascript
复制
{
    "courseName": "Unmatching", // no letter "D"
    "teachers": [
        {
            "firstName": "Dany",
            "lastName": "Kallas"
        }
    ]
}

您的查询无论如何都会返回它,因为学生文档中的其他课程与您的regex匹配。

你能做的是:

  1. 对具有匹配课程名称的文档的查询(.find())
  2. 手动过滤它们-循环遍历每一项以检查其名称是否与regex匹配。

示例数据:

代码语言:javascript
复制
// 1
{
    "_id" : ObjectId("5a019896f89c24926108e2bf"),
    "firstName" : "Sarah",
    "lastName" : "Jepsen",
    "age" : 27,
    "courses" : [ 
        {
            "courseName" : "Lorem",
            "teachers" : []
        },
        {
            "courseName" : "Ipsum",
            "teachers" : []
        },
        {
            "courseName" : "Dolor",
            "teachers" : []
        },
        {
            "courseName" : "Sit",
            "teachers" : []
        },
        {
            "courseName" : "Dolor 2",
            "teachers" : []
        }
    ]
},
// 2
{
    "_id" : ObjectId("5a019896f89c24926108e2be"),
    "firstName" : "John",
    "lastName" : "Smith",
    "age" : 22,
    "courses" : [ 
        {
            "courseName" : "Dioptry",
            "teachers" : []
        },
        {
            "courseName" : "Dino",
            "teachers" : []
        },
        {
            "courseName" : "A",
            "teachers" : []
        },
        {
            "courseName" : "B",
            "teachers" : []
        },
        {
            "courseName" : "C",
            "teachers" : []
        }
    ]
}

查询和筛选代码:

代码语言:javascript
复制
student.findCourses = (fcallback) => {

    var regexp = new RegExp('D');

    global.db.collection('students').find({ "courses.courseName": { $regex: regexp } }, { _id: 0, courses: 1 } }).toArray((err, result) => {

        // here, you'll receive:
        // [{ courses: [] }, { courses: [] }]
        // with all the courses inside
        // no matter if their names match the given regex
        // as it's enough that one of them does
        // to return the whole document

        // filtering:
        var filtered = result.map(student => {
            student.courses = student.courses.filter(course => regexp.test(course.courseName));
            return student;
        });

        // now, your filtered has exactly the same format
        // [{ courses: [] }, { courses: [] }]
        // but only with courses matching the regexp inside it

        console.log(JSON.stringify(filtered);

        // what you can do to get flat courses array is:
        var flat = filtered.reduce((p, c) => p.concat(c.courses), [])

        console.log(JSON.stringify(flat));


        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        console.log(jOk)
        console.log(JSON.stringify(result))
        return fcallback(false, jOk)
    })
}
票数 1
EN

Stack Overflow用户

发布于 2017-11-07 16:39:51

你试过这个吗?

代码语言:javascript
复制
global.db.collection('students')
    .find({ "courses.courseName": { $regex: new RegExp('D') }, _id: false })

我认为MongoDB客户端可以理解RegExp或字符串文本模式,但我认为您可能在这里混合了两个不同的模式。如果你把"/D/"放在你的名字里,你要找的是一门包含字面/D/的课程,而不仅仅是D

相关:MongoDB Regular Expression Search - Starts with using javascript driver and NodeJS

编辑:

_id: false是干什么用的?如果试图执行投影(并删除_id字段),则语法不正确。{ _id: false }应该作为第二个参数传递给.find()。当前查询与regex匹配,并检查_id是否等于false

代码语言:javascript
复制
global.db.collection('students')
    .find({ "courses.courseName": { $regex: /D/ } }, { _id: false })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47162993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档