我想使用以下限制来查询我的数据库,以获取满足这些条件的所有记录:
属性
是propertyID
active
为true
startDate
不大于 YendDate
不小于 X
我很难让 MongoDB 接受我的 $match
:
$match:{
$and:[
{ property : propertyID },
{ active : true },
{ $not: { start : {$gte: 1498780800 } } },
{ $not: { end : {$lte: 1497052800 } } }
]
}
现在我收到错误:MongoError:未知的顶级运算符:$not
。您可能会说只要 startDate
小于 X 且 endDate
小于 Y,但这不会起作用,因为 startDate
可能大于 X 并且endDate
小于 Y,这是我想要的记录等。这就是为什么这不起作用。我该如何解决这个问题?
更新:
我的逻辑不正确,这就是我想做的......
最佳答案
问题是你有 $not
在错误的地方。每the documentation :
Syntax:
{ field: { $not: { <operator-expression> } } }
因此,$not
不应该用作顶级运算符,该字段应该位于顶级。
关于这个问题的逻辑方面。您想要选择记录,其中 start
位于限制日期或 end
之间在限制日期之间,没有理由使用 $not
这里。另外,请确保您检查的值大于最小值且小于最大值,而不是相反。尝试以下查询:
$match: {
$and: [
{ property: propertyID },
{ active: true },
{ $or: [
{ start: { $lte: 1498780800, $gte: 1497052800 } },
{ end: { $lte: 1498780800, $gte: 1497052800 } }
] }
]
}
这将检查是否 start
或end
处于限制日期之间。
关于mongodb - $not 运算符在查询中的 $and 运算符内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349727/