Posted this to stackoverflow, but felt a cross-post here was sensible.
One thing I’ve noticed is that Filters.in
doesn’t work and I have to use new Document("$in", Arrays.asList(userId, "$owners))
Is there a separate helper function for “Aggregate in”, and are there any other errors or improvements I could make?
The aim is
- In the batches table is an entry per list of ‘primary batch for this list’
- In the table of list items is a large collection of lists
- I want
- All the items with a particular status
- Where the given userId is in the owners or readers
- And where it is in the primary batch
Here’s my pipeline, which was generated in new Document() style in Compass, but I altered to use helpers for readability.
MongoCollection<Document> batches = mongoTemplate.getCollection("batches")
Bson lookup = Aggregates.lookup("listItems", // from
Arrays.asList(
new Variable<>("listId", "$listId"),
new Variable<>("batchId", "$latestBatch")), // let
Arrays.asList(
Aggregates.match(Filters.expr(Filters.eq("status"), statusVar))),
Aggregates.match(Filters.expr(Filters.or(
Filters.in("owners", userId),
Filters.in("readers", userId)
))),
Aggregates.match(Filters.expr(Filters.and(
Filters.eq("listId", "$listId"),
Filters.eq("batch", "$batchId")
)))
), // pipeline
"listItems"); // as
Bson project = Aggregates.project(new Document("listItems", 1L));
batches.aggregate(Arrays.asList(lookup, project));