pibou
pibou

Reputation: 51

How can I filter sub-documents from MongoDB with SpringBoot?

I have documents in a collection such as :

{
  "login":"xxx",
  "someAttribute":"someValue",
  "subDocs":[
    {
      "data": "val1",
      "subDocNestedArray":["WWW","AAAA"]
    },
    {
      "data": "val2",
      "subDocNestedArray":["AAAA"]
    },
    {
      "data": "val3",
      "subDocNestedArray":["ZZZ"]
    }
    ]
}

I retrieve all documents that match login="xxx" and subDocNestedArray="AAAA" but want only subDocs matching along other properties of the root document, ex :

{
  "login":"xxx",
  "someAttribute":"someValue",
  "subDocs":[
    {
      "data": "val1",
      "subDocNestedArray":["WWW","AAAA"]
    },
    {
      "data": "val2",
      "subDocNestedArray":["AAAA"]
    }
    ]
}

I have tried with :

Aggregation.unwind("$subDocs"),
Aggregation.match(Criteria.where("subDocs.subDocNestedArray").is("AAAA")),
Aggregation.group("$_id")

that results in missing fields

{
  "login": null,
  "someAttribute": null,
  "subDocs":[
    {
      "data": "val1",
      "subDocNestedArray":["WWW","AAAA"]
    },
    {
      "data": "val2",
      "subDocNestedArray":["AAAA"]
    }
    ]
}

I did not manage to find the syntax using "redact".

Any clue ?

Make my MongoDB query return filtered results

Upvotes: 3

Views: 45

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can try this:

MatchOperation match = match(Criteria.where("login").is("xxx").and("subDocs.subDocNestedArray").is("AAAA"));
AddFieldsOperation addField = AddFieldsOperation.addField("subDocs").withValueOf(ArrayOperators.Filter.filter("subDocs").as("item").by(ArrayOperators.In.arrayOf("$$item.subDocNestedArray").containsValue("AAAA")));
Aggregation agg = Aggregation.newAggregation(match, addField);
AggregationResults<XYZClass> aggResults = mongoTemplate.aggregate(agg, "CollectionName",XYZClass.class);

In this, we have a $match stage to filter documents, and then an addFields stage, to filter the subDocs array. Please test it out.

Upvotes: 1

Related Questions