来自 MongoCharts 的 NODE JS + Mongodb 聚合管道

时间:2021-04-28 08:57:13

标签: mongodb aggregation-framework aggregation mongodb-charts

目前无法弄清楚为什么一个管道工作而另一个不工作。我从 MongoDB 图表中获得了两个管道,它们都返回了一些东西并在 MongoDBCharts 上显示了图表。但是,当我在代码中使用它们时,只有第一个管道返回一些东西。我对所有案例都使用了相同的数据。任何建议将不胜感激!

第一个不过滤过去 30 天(由 Mongo 硬编码),两个管道都是从 Mongodb 图表复制的,没有改变。

import java.util.Scanner;

public class Main{
   public static void main (String[] args) {

        try {

            Candidate c = getCandidateDetails();
            System.out.println(c.toString());
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }           

    }

   public static Candidate getCandidateDetails() throws InvalidSalaryException{
       Scanner sc = new Scanner(System.in);
       String name = sc.nextLine();
       String gender = sc.nextLine();
       double expectedSalary = sc.nextDouble();
       if(expectedSalary < 10000){
           throw new InvalidSalaryException("Registration Failed. Salary cannot be less than 10000.");
       }
       return new Candidate(name,gender,expectedSalary);    
   }
}


record Candidate(String name, String gender, double salary){}

class InvalidSalaryException extends IllegalArgumentException{
    public InvalidSalaryException(String str){
        super(str);
    }
}

第二个

[
  {
    "$addFields": {
      "trigger_time": {
        "$convert": {
          "input": "$trigger_time",
          "to": "date",
          "onError": null
        }
      }
    }
  },
  {
    "$match": {
      "event_type": {
        "$nin": [
          null,
          "",
          "AC Lost",
          "Device Lost",
          "logged into Database",
          "logged into Nexus Database",
          "logged out of Nexus Database",
          "Low Battery"
        ]
      }
    }
  },
  {
    "$addFields": {
      "trigger_time": {
        "$cond": {
          "if": {
            "$eq": [
              {
                "$type": "$trigger_time"
              },
              "date"
            ]
          },
          "then": "$trigger_time",
          "else": null
        }
      }
    }
  },
  {
    "$addFields": {
      "__alias_0": {
        "hours": {
          "$hour": "$trigger_time"
        }
      }
    }
  },
  {
    "$group": {
      "_id": {
        "__alias_0": "$__alias_0"
      },
      "__alias_1": {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "__alias_0": "$_id.__alias_0",
      "__alias_1": 1
    }
  },
  {
    "$project": {
      "y": "$__alias_1",
      "x": "$__alias_0",
      "_id": 0
    }
  },
  {
    "$sort": {
      "x.hours": 1
    }
  },
  {
    "$limit": 5000
  }
]

1 个答案:

答案 0 :(得分:0)

我最终解决了自己的问题。经过一番挖掘和询问。 Node.js 在使用 '$date' 时对 Mongodb 做了一些有趣的事情,这就是管道不起作用的原因。

解决方案是删除“$date”并传入一个日期对象。就我而言,

"trigger_time": {
        "$gte": new Date("2021-03-29T08:35:47.804Z")
      }