Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Spring Data Mongo Reactive, nested @DbRef can be eagerly loaded by using the Aggregation.lookup() method in the Aggregation class.

Here's an example code snippet:

public Mono<MyDocument> getMyDocumentWithNestedDbRef(String id) {

    // define aggregation pipeline to lookup referenced documents
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(Criteria.where("_id").is(id)),
            Aggregation.lookup("referencedCollectionName", "nestedIdField", "referencedIdField", "nestedObjects")
    );

    // execute aggregation pipeline and return result as Mono<MyDocument>
    return mongoTemplate.aggregate(aggregation, "myCollectionName", MyDocument.class)
            .map(aggregationResults -> aggregationResults.getUniqueMappedResult());
}

In the above code, we first define an Aggregation pipeline that matches the document with the given id and then performs a lookup on the referenced collection (referencedCollectionName) using the nestedIdField in the current document and referencedIdField in the referenced document. We also specify an alias (nestedObjects) for the returned collection of referenced documents.

Finally, we execute the aggregation pipeline using mongoTemplate.aggregate() method and return the result as a Mono<MyDocument> object. This result will have the nested @DbRef objects eagerly loaded.