Closed sunmingtao closed 5 years ago
Good implementation:
private Bson buildLookupStage(){
List<Variable<String>> let = new ArrayList<>();
let.add(new Variable<String>("id", "$_id"));
// lookup pipeline
Bson exprMatch = Document.parse("{'$expr': {'$eq': ['$movie_id', '$$id']}}");
Bson lookupMatch = Aggregates.match(exprMatch);
List<Bson> lookUpPipeline = new ArrayList<>();
// lookup sort stage
Bson sortLookup = Aggregates.sort(Sorts.descending("date"));
lookUpPipeline.add(lookupMatch);
lookUpPipeline.add(sortLookup);
return Aggregates.lookup("comments", let, lookUpPipeline, "comments");
}
public Document getMovie(String movieId){
if (!validIdValue(movieId)) {
return null;
}
List<Bson> pipeline = new ArrayList<>();
// match stage to find movie
Bson match = Aggregates.match(Filters.eq("_id", new ObjectId(movieId)));
pipeline.add(match);
// comments lookup stage
Bson lookup = buildLookupStage();
if(lookup != null) {
pipeline.add(lookup);
}
Document movie = moviesCollection.aggregate(pipeline)
.batchSize(1)
.iterator().tryNext();
return movie;
}
Ticket https://university.mongodb.com/mercury/M220J/2019_October/chapter/Chapter_2_User-Facing_Backend/lesson/5bb67087b9a628479e54b95e/problem
My implementation (bad)