如何动态构建mongodb查询 [英] How to dynamically build mongodb query
问题描述
我在mongodb聚合中有一个match表达式.比赛中包含3个字段,但它们并不总是包含数据.如果字段不为空,我只想在比赛中包括这些字段.
I have a match expression in a mongodb aggregation. There are 3 fields that are included in the match but they don't all always contain data. I only want to include the fields in the match if the field isn't empty.
如果所有字段都有数据,但是例如,如果用于studentGradeLevels
的数组为空,则匹配看起来是这样,那么我不想包含它,或者我希望查询仍然返回数据而忽略空参数.
This is what the match looks like if all fields have data but for example, if the array used for studentGradeLevels
is empty, then I don't want to include it or I want the query to still return data ignoring the empty parameter.
$match: {
"school._id": "7011",
"studentGradeLevels": { $in: ["09", "10", "11", "12"] },
"contentArea": {
$in: [
"English 1"
]
}
}
有没有一种方法可以动态构建匹配项,以便仅包含我要基于的字段是否为空,或者在查询中执行某些操作以忽略空的参数.
Is there a way to either dynamically build the match so that I only include the fields I want based on if they are empty or not or do something in the query so that parameters that are empty are ignored.
推荐答案
您可以使用 $nin
当数组为空时,这样将不考虑匹配字段($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
}
}])
这篇关于如何动态构建mongodb查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!