【问题标题】:Mongodb Aggregation in Node.js to Spring BootNode.js 中的 Mongodb 聚合到 Spring Boot
【发布时间】:2021-08-15 11:28:47
【问题描述】:

我需要查询出生日期(dob)的日期和月份与当前日期加7天相同的客户列表。

下面是 node.js 中的查询。但是,我终生无法弄清楚如何将聚合转换为 Spring Boot。

//node.js
let date = moment();
    date = date.add(7, "day");
    db.customers.aggregate([
        { $match: { companyId: "COMPANY_ID" } },
        {
            $project: {
                customerName: 1,
                phone: 1,
                _id: 1,
                dob: 1,
                month: { $month: { $add: [new Date(), "$dob"] } },
                date: { $dayOfMonth: { $add: [new Date(), "$dob"] } },
                customerGroupId: 1,
                customerGroup: 1,
            }
        },
        {
            $match: {
                month: date.get("month"), date: date.get("date")
            }
        } 


//partially in spring boot.

public List<Customers> findCustomersByDOB (String companyId) {
        List<AggregationOperation> list = new ArrayList<AggregationOperation>();
        list.add(Aggregation.match(Criteria.where("companyId").is(companyId)));
        list.add(Aggregation.project("companyId", "customerName", "customerGroup", "phone", "dob"));
        TypedAggregation<Customers> agg = Aggregation.newAggregation(Customers.class, list);
        
            return mongoOperations.aggregate(agg, Customers.class, Customers.class).getMappedResults();
    }

【问题讨论】:

  • 我没有使用 Dates。但是你试过pingax.com/…
  • 感谢您的提示!我会记住这一点的。

标签: node.js mongodb spring-boot mongodb-query aggregate


【解决方案1】:

我想你可以试试这个。

list.add(Aggregation.project("companyId", "customerName", "customerGroup", "phone", "dob")
.andExpression("month(toDate(dob))").as("month")
.andExpression("dayOfMonth(toDate(dob))").as("day"));

【讨论】:

    【解决方案2】:

    非常感谢!有用! :)

    public List<Customers> findCustomersByDOB(String companyId) {
                 LocalDate localDate = LocalDate.now();
                 LocalDate newDate = localDate.plusDays(7);
         List<AggregationOperation> list = new ArrayList<AggregationOperation>();
                 list.add(Aggregation.match(Criteria.where("companyId").is(companyId)));
                 list.add(Aggregation.project("companyId", "customerName", "customerGroup", "phone", "dob")
                         .andExpression("month(toDate(dob))").as("month").andExpression("dayOfMonth(toDate(dob))").as("day"));
        list.add(Aggregation.match(Criteria.where("month").is(newDate.getMonthValue()).and("day").is(newDate.getDayOfMonth())));
        TypedAggregation<Customers> agg = Aggregation.newAggregation(Customers.class, list);
                
                    return mongoOperations.aggregate(agg, Customers.class, Customers.class).getMappedResults();
        }
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2018-07-07
      • 2021-04-03
      • 1970-01-01
      相关资源
      最近更新 更多