如何使用多个OR动态构建MongoDB查询? [英] How to dynamically build MongoDB Query with multiple OR?

查看:73
本文介绍了如何使用多个OR动态构建MongoDB查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用具有多个OR的Node动态构建Mongo查询.该查询的重点是使用多个搜索词在数据库中进行AND搜索.

I would like to be able to dynamically build a Mongo query using Node with multiple OR's. The point of this query is to do an AND search in the database with multiple search terms.

例如,假设某人想要搜索包含单词"dog"和谷物"的记录.该查询将仅返回记录中某处具有"dog"和谷物"的记录(即搜索字词可以出现在不同的列中).

For example, suppose someone wanted to search for records containing the words "dog" and "cereal." The query would only return records that have "dog" and "cereal" somewhere in the record (i.e. the search terms can appear in different columns).

我知道查询最终应该像这样:

I know that the query should end up looking like this:

query = {
    $and: [
        {$or: [
            {col1: {$regex: "first", $options: "i"}},
            {col2: {$regex: "first", $options: "i"}}
        ]},
        {$or: [
            {col1: {$regex: "second", $options: "i"}},
            {col2: {$regex: "second", $options: "i"}}
        ]}
    ]
}

但是,我的节点代码不会产生此错误. 这是我得到的最接近的答案:

My node code, however, does not produce this. This is the closest I have gotten to figuring this out:

var regexQueryWrapper = {};
regexQueryWrapper["$and"] = [];
var wrapper = {};
wrapper["$or"] = [];
var query = {};
searchTerms.forEach(function(term) {
    searchFields.forEach(function(field) {
        query[field] = {$regex: term, $options: 'i'};
        wrapper["$or"].push(query);
    });
    regexQueryWrapper["$and"].push(wrapper);
});

做到这一点的最佳方法是什么?我缺少其他方法吗?

What is the best way to do this? Is there a different approach that I am missing?

推荐答案

您已经关闭.您似乎正在重用对象.以下是一些经过调整的代码,这些代码可构建您要查找的查询,并在每次forEach迭代中重新初始化临时对象:

You're close. You seem to be reusing objects. Here's some adjusted code that builds the query you're looking for, with the temporary objects reinitialized on each forEach iteration:

var regexQueryWrapper = {};
regexQueryWrapper["$and"] = [];

searchTerms.forEach(function(term) {

    var wrapper = {"$or": []};

    searchFields.forEach(function(field) {
        var query = {};
        query[field] = {$regex: term, $options: 'i'};
        wrapper["$or"].push(query);
    });

    regexQueryWrapper["$and"].push(wrapper);

});

以及使用map的替代实现:

var query = {"$and": searchTerms.map(function(term) {

    return {"$or": searchFields.map(function(field) {

        var o = {};
        o[field] = {"$regex": term, "$options": "i"};
        return o;

    })};

})};

这篇关于如何使用多个OR动态构建MongoDB查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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