db.customers.aggregate( { $match: {'mccStatistics.id': {$in: [7011,5812]}}}, { $unwind: '$mccStatistics'}, { $match: {'mccStatistics.id': {$in: [7011,5812]}}}, { $group: {_id: '$_id', mccStatistics: {$push: '$mccStatistics'}}})Mongodb 3.2 provides a new features to operate arrays and this approach works more faster. This new approach really fast
As hinted by Hakan, you could parse $filter through Document class. Using your test collection example see below:
Document match = Document.parse("{ $match: {'test.id': {$in:[7011, 5812] } }}");
Document project = Document.parse("{ $project: { test: { $filter: { input: '$test', as:'item', cond:{$or: [{$eq:['$$item.id', 7011]}, {$eq:['$$item.id', 5812]}]}}}}} ");
List<Document> pipeline = asList(match, project);
AggregateIterable<Document> iterable = db.getCollection("test").aggregate(pipeline);
The above snippet is tested on MongoDB Java Driver v3.2.2 and v3.4.2. Aggregation operator $filter is available on MongoDB v3.2+.
but doesn’t eliminate requirement for $filter stage inside the driver.
Currently MongoDB Java Driver provides typed builders only for aggregation stages and accumulators, but not the full expression language (which $filter is part of ). There is currently an open tracking ticket for this support JAVA-1949. Please feel free to up-vote or add yourself as a watcher for updates on the ticket.
Regards,
Wan.