How to dynamically build mongodb query

安稳与你 提交于 2019-12-06 08:08:02

You can use $in when the array is not empty and $nin when the array is empty, this way the match field will not be taken into account ($nin : []):

function buildMatch(arr) {
    var matcher = {};
    if (arr.length == 0)
        matcher["$nin"] = arr;
    else
        matcher["$in"] = arr;
    return matcher;
}

var grades = ["09", "10", "11", "12"];
var areas = [ "English 2" ];

var gradeMatch = buildMatch(grades);
var areaMatch = buildMatch(areas);

db.students.aggregate([{
    $match: {
        "school._id": "7011",
        "studentGradeLevels": gradeMatch,
        "contentArea": areaMatch
    }
}])

A variation: Check fields for existence and if so, change to a special value e.g. _ and add that to the $inlist:

db.foo.aggregate([
{$project: {"studentGradeLevels":{$ifNull: ["$studentGradeLevels","_"]},
            "contentArea":{$ifNull: ["$contentArea","_"]}
}}
,{$match: {
        "studentGradeLevels": { $in: ["_", "09", "10", "11", "12"] },
        "contentArea": { $in: [ "_", "English 1" ]  }
}}
              ]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!