我的基本结构是我有一个 User 对象和一个包含 subjectId 和每小时价格的会话对象。
User{
defaultHourly: Number,
subjects{
[
id: String,
hourly: Number
]
}
}
我这样使用 elemMatch:
query.elemMatch("subjects", {
"id": { $in: subjects },
"$or": [
{ "hourly": { $eq: null } }, // this is my issue
{
"$and": [
{ "hourly": { $ne: null } },
{ "hourly": { $gte: price.low, $lte: price.high } }
]
}
]
});
elemMatch 的第一部分确保我想要的 subjectId 位于主题数组中。然后我想按价格过滤。如果用户的每小时字段为空,我想将defaultHourly与price.low和price.high进行比较。
问题是 defaultHourly 不是主题中的字段,而是主题父级中的字段,因此我不确定如何访问它。
我想写:
"$or": [
{
"$and": [
{ "hourly": { $eq: null } },
{ "defaultHourly": { $gte: price.low, $lte: price.high } } //this doesnt work because default hourly is not a field.
]
},
{
"$and": [
{ "hourly": { $ne: null } },
{ "hourly": { $gte: price.low, $lte: price.high } }
]
}
]
});
我怎样才能进行这种多级比较?