2

i have spring mongoDB collection user with data as bellow:

    [{
  "_id": {
    "$oid": "5fd81fb277b245717d34c25e"
  },
  "userName": "banana",
  "email": "banana",
  "userRole": {
    "$ref": "roles",
    "$id": {
      "$oid": "5fdc248b1846a46d71a71374"
    }
  }
},{
  "_id": {
    "$oid": "5fd81fd777b245717d34c25f"
  },
  "userName": "banana",
  "email": "banana",
  "userRole": {
    "$ref": "roles",
    "$id": {
      "$oid": "5fd6e784f03b1f5e76699ebb"
    }
  }
},{
  "_id": {
    "$oid": "5fdc24691846a46d71a71373"
  },
  "userName": "banana",
  "email": "banana",
  "userRole": {
    "$ref": "roles",
    "$id": {
      "$oid": "5fd6e784f03b1f5e76699ebb"
    }
  }
},{
  "_id": {
    "$oid": "5fe19f2f136f696e0bf83167"
  },
  "userName": "banana",
  "email": "banana",
  "userRole": {
    "$ref": "roles",
    "$id": {
      "$oid": "5fdc248b1846a46d71a71374"
    }
  }
}]

I try to apply Aggregation on it with Spring MongoDB

GroupOperation groupOperation = Aggregation.group("userRole.$id")
                .addToSet("email").as("email")
                .addToSet("firstName").as("firstName");

        Aggregation aggregation = Aggregation.newAggregation(groupOperation);

        AggregationResults<Map> result = mongoOperations
                .aggregate(aggregation, "user", Map.class);
        return result.getMappedResults();

But it not work. My question is does Spring MongoDB Aggregation support DBref ?

Tung Vo
  • 2,227
  • 5
  • 27
  • 45

1 Answers1

2

Spring data mongo does support aggregation, you can read more about it here - https://www.baeldung.com/spring-data-mongodb-projections-aggregations

Based on the collection example you have provided, I don't see any field named as firstName, were you perhaps referring to userName and based on the aggregation you've provided is it similar to this:

db.collection.aggregate({
  "$group": {
    "_id": {
      "userRole": "$userRole.$id"
    },
    "email": {
      "$addToSet": "$email"
    },
    "username": {
      "$addToSet": "$userName"
    }
  }
})

If so, then you can directly add this pipeline to your repository method. Something like this

public interface UserRepository extends MongoRepository<User, String> {
    
     @Aggregation(pipeline = {
        "{ \"$group\": { \"_id\": { \"userRole\": \"$userRole.$id\" }, \"email\": { \"$addToSet\": \"$email\" }, \"username\": { \"$addToSet\": \"$userName\" } } }"
     })
     AggregationResults<Result> findAndGroup();
}

*Note - Here Result is the class which has fields equivalent to the returning document

And then


@Autowired
private UserRepository userRepository;

userRepository.findAndGroup().getMappedResults();