Skip to content

delete where all keys of a map are contained in a list in mongodb

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:

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?



This could be also an answer:

    "$project": {
      "mapAsArray": {
        "$objectToArray": "$map"
    "$match": {
      "mapAsArray": {
        "$not": {
          "$elemMatch": {
            "k": {
              $nin: [

Here the mongoplayground

The map to spring-data-mongodb:

ProjectionOperation projectionOperation = project()

MatchOperation matchOperation = match(where(myMapToArray)

AggregationResults<myObject> aggregate = mongoTemplate.aggregate(newAggregation(projectionOperation, matchOperation),
            myObject.class, myObject.class);
10 People found this is helpful