按时钟范围查询mongo文档 - 正向和反向

时间:2015-02-11 19:32:34

标签: javascript mongodb mongoose mongodb-query

商业案例:我不希望检索那些不想在一天中的工作时间内(如下班时间)检索的用户。

在靠近此

的架构上
{
  'name': String,
  'from': Number, // 800 (8:00 AM)
  'to': Number, // 1700 (5:00 PM)
  ...
}

我正在使用聚合来获取用户,同时还在其他操作中展开子文档数组。基本搜索条件位于$match运算符中,如下所示。

User.aggregate([
  {
    // some aggregation stuff
  },
  {
    $match: {
      $and: [
        { 'from': { $lte: currentTime },
        { 'to': { $gte: currentTime }
      ]
    }
  }
]);

问题: 如何允许用户设置反向范围 ?像早上8点到早上8点。如何编写有助于此的查询?今天没留下任何头发。

1 个答案:

答案 0 :(得分:1)

对于"正常"范围如上午9点到下午5点,查询条件是

{ "$match" : { "from" : { "$lte" : ct }, "to" : { "$gte" : ct } } }

$and是不必要的,因为它是隐含的)而对于"反向"范围如下午8点到8点,查询条件是

{ "$match" : { "$or" : [{ "from" : { "$gte" : ct } }, { "to" : { "$lte" : ct } }] } }

两种类型的范围的逻辑是不同的,因此您应该为反向范围添加新字段:

{
    "name" : "Jerry",
    "rfrom" : 2000,
    "rto" : 800
}

然后使用匹配

进行聚合
{ "$match" : { "from" : { "$lte" : ct }, "to" : { "$gte" : ct } } }

{ "$match" : { "$or" : [{ "rfrom" : { "$gte" : ct } }, { "rto" : { "$lte" : ct } }] } }

或一个具有两个$match条件分离的聚合:

{ "$match" : { "$or" : [
    { "from" : { "$lte" : ct }, "to" : { "$gte" : ct } },
    { "$or" : [{ "rfrom" : { "$gte" : ct } }, { "rto" : { "$lte" : ct } }] }
] } }

或者,可能存在一种聪明的方式来存储适用于"正常"和"反向"一个查询中的范围,但我在5分钟内无法想到它。