【问题标题】:Trying to find with $regex multiple fields at the same time in Mongodb尝试在 Mongodb 中同时使用 $regex 查找多个字段
【发布时间】:2021-03-31 23:57:44
【问题描述】:

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

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

我正在使用 $regex 将搜索与我的应用程序匹配。所以我在我的服务器 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 中的文档,但我找不到它...

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

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

    这里是你可以尝试的示例代码。

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

    【讨论】:

    • 完美!确切地说,我缺少 OR 运算符...谢谢!
    【解决方案2】:

    OR 运算符、正则表达式或选项不需要用引号引起来。以下对我有用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2018-11-17
      • 2022-10-15
      相关资源
      最近更新 更多