尝试在 Mongodb 中同时使用 $regex 查找多个字段 [英] Trying to find with $regex multiple fields at the same time in Mongodb

查看:108
本文介绍了尝试在 Mongodb 中同时使用 $regex 查找多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的网络应用程序中开发一个搜索器,我正在使用 mongodb ......所以......我有一个包含这些信息的文档.

I am trying to develope a searcher in my web app, i am using mongodb... so... i have a document, with this information.

{
    "_id": "458734895734",
    "name": "user",
    "ref": "1",
    "data": "fdnsfkjndjfn"
},
{
    "_id": "3332423333",
    "name": "user1",
    "ref": "2",
    "data": "dvsdvdvds"
}

我正在使用 $regex 将搜索与我的应用程序相匹配.所以我在我的服务器 node.js 中有这个.

i am using $regex for match the search with my app. so i have this in my server node.js.

db.users.find({ 
    name: {'$regex': query, '$options': 'i'}
}).then((users) => {
    res.json(users);
})

        // var query, is just the pattern that i send from my web

如您所见,我的服务器仅在名称"字段中搜索,如何添加其他字段(如引用")并同时在两个字段中搜索?我已经检查了 mongodb 中的文档,但我找不到它...

As you can see, my server is only searching in the field 'name', how can i add other field like 'ref' and search in both fields at the same time?? i've checking the documentation in mongodb but i could not find it...

推荐答案

这是因为你编写查询的方式意味着它应该匹配给定的 regex 查询和所有传递的参数,如 and(&&) 操作.您可以做的是对所有必填字段进行和或(||)操作.

This is because the way you wrote the query which means it should match the given regex query with all passed parameter like and(&&) operation. What you could do is make and or(||) operation with all the required fields.

这是您可以尝试的示例代码.

Here the sample code you can try.

db.users.find({
    "$or": [
        { name: { '$regex': query, '$options': 'i' } },
        { ref: { '$regex': query, '$options': 'i' } }
    ]
}).then((users) => {
    res.json(users);
});

这篇关于尝试在 Mongodb 中同时使用 $regex 查找多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆