I have this:
- A field which is a map where the keys are UUIDs and the value another object which is not relevant.
- A list of UUIDs that should be passed as parameter.
I want to:
delete from the collection all documents where all keys of the map are included in the list of UUIDs
The object:
@Document public class MyClass { private Map<UUID, anotherObject> myMap; }
With derived queries I am not able to reach the UUID because has no name -> deleteByMyMap…
And with a query I know that there is a way to convert the map into an array ($expr and $objectToArray) but I do not know if it makes sense.
- Is there any way to do this?
- How can I access just the key of the map?
Advertisement
Answer
This could be also an answer:
db.collection.aggregate([ { "$project": { "mapAsArray": { "$objectToArray": "$map" } } }, { "$match": { "mapAsArray": { "$not": { "$elemMatch": { "k": { $nin: [ "3478956c-3a01-404f-84e7-2a076e165215", "1e1d1efb-5bf9-48ac-93ca-4a2df5a9f7eb" ] } } } } } } ])
Here the mongoplayground
The map to spring-data-mongodb:
ProjectionOperation projectionOperation = project() .and(ObjectOperators.valueOf(myMap).toArray()).as(myMapToArray); MatchOperation matchOperation = match(where(myMapToArray) .not() .elemMatch(where("k").nin(myList))); AggregationResults<myObject> aggregate = mongoTemplate.aggregate(newAggregation(projectionOperation, matchOperation), myObject.class, myObject.class);