3

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

pibou
  • 51
  • 5

1 Answers1

1

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.

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
  • Works fine, thank you. I discovered the Filter operator but did not understand its syntax., I had no idea of the AddFieldsOperation part – pibou Jun 14 '23 at 09:46
  • 1
    Filter creates an expression, whereas AddFields is an aggregation stage, it can add new fields to the document or update existing fields as well. @pibou – Charchit Kapoor Jun 14 '23 at 15:12