Gagan Noor Singh
Gagan Noor Singh

Reputation: 41

Getting wrong data while fetching one-to-one data using Springboot Mongo Repository @DocumentReference

I have two documents "Employee" and "Organisation", I am trying to fetch Employee data by ID and with this I wanted to fetch Organisation data.

Employee Document: ID, Name, Email, UnitId

Organisation Document: ID, OrgName, UnitId

In Employee Entity:

@ReadOnlyProperty
@DocumentReference(lookup = "{'unitId':? #{#target.unitid}}")
private Organisation organisation;

While fetching employee by Id the data is returned by Organisation data is not correct.

Employee emp = empRepository.findByEmployeeId(employeeid);

Result:

{
    "id": "777449",
     "firstname": "test",
    "email": "[email protected]",
    "unitId": "SUP72120",
    "organisation": {
        "id": "xxxx-xxxx",
        "unitid": "900723",
        "orgName":"name of org" 
    }
}

The Organisation data is the first document from collection, I wanted to fetch the organisation with unitid from employee document.

Upvotes: 0

Views: 75

Answers (1)

Gagan Noor Singh
Gagan Noor Singh

Reputation: 41

@Aggregation({ "{$match: {employeeId: ?0}}", "{$lookup: {from: 'Organisation', localField: 'unitId', foreignField: 'unitid', as: 'organisation'}}", "{$unwind : '$organisation'}" })

Added above aggregation in repository and it worked fine

Upvotes: 0

Related Questions