簡體   English   中英

查找操作后的項目嵌入文檔字段

[英]Project embedded document fields after lookup operation

我想在時間表之間進行連接:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = TIMESHEET_COLLECTION)
public class Timesheet {

    @Id
    private ObjectId id;
    private ObjectId employeeId;
    private LocalDate date;
    private String occupationTitle;
    private BigDecimal salary;
    private List<TimesheetEntry> entries;
}

和員工(作為嵌入式文檔):

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = Employee.EMPLOYEE_COL)
public class Employee {

    @Id
    private ObjectId id;
    private String registry;
    private String cpf;
    private String firstName;
    private String lastName;
    private String nickname;
    private String phone;
    private LocalDate dateOfBirth;
    private LocalDate admissionDate;
    private EmployeeOccupation occupation;
    private EmployeePaymentPreferences paymentPreferences;
    private Map<String, String> equipmentPreferences;
    private Boolean active;
}

所以我有這個聚合查詢,帶有matchlookupunwind投影操作。

Aggregation aggregation = Aggregation.newAggregation(matchTimesheetFilter(timesheetFilter), lookupEmployee(), unwindEmployee(), projectEmployee());

有查找和展開實現。 我正在放松,因為員工應該是一個單一的對象,而不是一個數組。

private LookupOperation lookupEmployee(){
    return LookupOperation.newLookup()
            .from("employee")
            .localField("employeeId")
            .foreignField("_id")
            .as("employee");
}

private UnwindOperation unwindEmployee(){
    return Aggregation.unwind("employee");
}

它成功返回一個帶有嵌入員工文檔時間表文檔 關鍵是:我不想要員工的所有數據 我只想要幾個字段

因此,我嘗試使用我的投影操作從員工中排除不需要的字段:

private ProjectionOperation projectEmployee() {
    return Aggregation.project().andExclude("employee.nickname", "employee.firstName", "employee.fullName");
}

它沒有用。 我的嵌入式員工仍然返回所有字段。 但是,如果我執行以下操作,我可以成功地從時間表中排除字段:

private ProjectionOperation projectEmployee() {
    return Aggregation.project().andExclude("startDate", "endDate");
}

如何從通過查找操作嵌入的文檔中投影自定義字段?

我認為你需要排除"employee.nickname", "employee.firstName", "employee.fullName" ,而不是"nickname", "firstName", "fullName"

嘗試這個:

private ProjectionOperation projectEmployee() {
    return Aggregation.project().andExclude("employee.nickname", "employee.firstName", "employee.fullName");
}

我是這樣做的(不確定它是否正確,但它有效):

private LookupOperation lookupEmployee(){
    return LookupOperation.newLookup()
            .from("employee")
            .localField("employeeId")
            .foreignField("_id")
            .as("employeeLookup");
}

no unwind used

Aggregation.project().and("employeeLookup.firstName"). as ("employee.firstName")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM