I have this query which works fine in mongodb:
db.document.aggregate([
{$match: { $and: [
{ type:ObjectId('abc') },
{ metadata: { $elemMatch: { metadataType: ObjectId("abc"), value: DBRef("tag", ObjectId("abc"))}}},
{ metadata: { $elemMatch: { metadataType: ObjectId("abc"), value: "abc"}}}
] }
},
{$project: {
metadata: {
$filter: {
input: "$metadata",
as: "metadata",
cond: { $or: [
{$eq: [ "$$metadata.metadataType", ObjectId("abc") ] },
{$eq: [ "$$metadata.metadataType", ObjectId("abc") ] }]}
}
}
}
How could I do this in JAVA using mongodb driver? I can do the $match stage but I don't know how to do the $project stage using $filter for the array.
I could use Document.parse() (like suggested here: https://groups.google.com/forum/#!topic/mongodb-user/W4wiPYk0Gec ) but I think it's pretty ugly. Or I could use something like here: Does Spring Data MongoDb support $filter array aggregations operator? But it's also not too pretty.
Basically my question is: is there a good/better way to do this in the newer versions of mongodb driver? (Something like the 3rd answer here for spring mongodb: Query a document and all of its subdocuments that match a condition in mongodb (using spring) )
***** EDIT
More precisely: Is there a way to do it like the match part here:
AggregateIterable<Document> output = document.aggregate(
Arrays.asList(
Aggregates.match(and(
eq("type", new ObjectId("abc")),
elemMatch("metadata", and(eq("metadataType", language), eq("value", abc))),
elemMatch("metadata", and(eq("metadataType", workClusterName), eq("value", "abc")))
)),
Aggregates.project(filterHOWTO)
));