$ not运算符在查询中的$和运算符内不起作用

时间:2017-06-04 00:23:11

标签: mongodb

我想使用以下限制查询我的数据库,对于 all 这些条件为真的所有记录:

  • propertypropertyID
  • activetrue
  • startDate不大于Y
  • endDate不小于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这是我想要的记录等等。这就是为什么它不会起作用。我该如何解决这个问题?

更新:

我的逻辑不正确,这就是我想要做的......

enter image description here

1 个答案:

答案 0 :(得分:2)

问题是您在错误的地方遇到$not。每the documentation

  

语法{ field: { $not: { <operator-expression> } } }

因此,$not不应该用作顶级操作符,该字段应该位于顶层。

这个问题的逻辑方面。您想要选择在{strong>或 start限制日期之间的end所在的记录 那里没有在此处使用$not的原因。此外,请确保检查的是否大于最小值且小于最大值,而不是相反。请尝试以下查询:

$match: {
  $and: [
    { property: propertyID },
    { active: true },
    { $or: [
      { start: { $lte: 1498780800, $gte: 1497052800 } },
      { end: { $lte: 1498780800, $gte: 1497052800 } }
    ] }
  ]
}

这将检查限制日期之间是start还是end