mongoTemplate fillter document array

37 Views Asked by At

Using mongoTemplate in java Spring I tried this, but I don't keep document structure

Document as:

{

   A :'a',
   B :'b',
   C : [
          { 
            name:'cat' ,  type :'animal'
          },
         { 
            name:'jonh' ,  type :'human'
          }
       ]
}

I want to keep document structure and filter c.type = 'animal' like below

Result example :

{

   A :'a',
   B :'b',
   C : [
          { 
            name:'cat' ,  type :'animal'
          },
         
       ]

}
1

There are 1 best solutions below

0
J.F. On

I think you are looking for this query where the document is not modified except for the filtering elements into C array where type is not animal.

So using MongoTemplate you can try something like this (not tested):

Aggregation aggregation = Aggregation.newAggregation(Aggregation.set("C",
    Aggregation.filter("C", Criteria.where("type").is("animal"))
));

List<YourDocumentClass> result = mongoTemplate.aggregate(aggregation, YourDocumentClass.class).getMappedResults();