2

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)
                ));
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
bartfer
  • 111
  • 1
  • 8

1 Answers1

0

You can do it with spring's MongoTemplate using MongoTemplate#aggregate and passing it a spring org.springframework.data.mongodb.core.query.Query object, which you build via a org.springframework.data.mongodb.core.query.Criteria builder pattern. The Criteria object has methods for elemMatch, etc. There are methods in Criteria for every aspect of the query you've posted here -- you just need to learn how to chain them together in the Criteria builder.

Blake
  • 986
  • 9
  • 24